Saturday, 13 November 2021

AWS Volume encryption automatically for all instances for your AWS environment automatically using Shell Script :


About EBS volume Encryption:

EBS encryption as an encryption solution for your EBS resources associated with your aws EC2 instances. With Amazon EBS encryption, you aren't required to build, maintain, and secure your own key management infrastructure. Amazon EBS encryption uses AWS KMS keys when creating encrypted volumes for the ec2 servers.

Encryption operations occur on the servers that host EC2 instances, ensuring the security of both data-at-rest and data-in-transit between an instance and its attached EBS storage volume .

Problem Statement : 

Encrypt Volume encryption is an challenging task in an existing production environment which was  not build with encryption during the environment build . If its an 200 + instance then manually creating the AMI and attaching and detaching the volume manually will take lots of time and its an error prone . 

Solution :

So I decide to automate that task for my client which will detach the unencrypted volume and create an snapshot of the unencrypted volume , create an AWS volume by tracking the availability zone of the previous instance and attach the volume with the instance .   

Script :

Note : Server need to be ins stop state to detach the volume . Also you can add one more liner check in the below script to check if instance is online or in stop state . if you  need help please write back i will update the script

#!/bin/bash

#Script to update unencrypted volume on the account

# Place the input of volume Id to be delete in /tmp/volid.txt


us_region_name='your volume region name'

describe_vol="/usr/bin/aws ec2 describe-volumes"

describe_instance="/usr/bin/aws ec2 describe-instances"

create_snapshot="/usr/bin/aws ec2 create-snapshot"

describe_snapshots="/usr/bin/aws ec2 describe-snapshots"

create_volume="/usr/bin/aws ec2 create-volume"

attach_volume="/usr/bin/aws ec2 attach-volume"

detach_volume="/usr/bin/aws ec2 detach-volume"

create_tags="/usr/bin/aws ec2 create-tags"

kms_key="your KMS key"

for SNAP in `cat /tmp/volid.txt`

do

echo $SNAP


instance_id=`$describe_vol  --volume-ids $SNAP  --query Volumes[*].Attachments[*].InstanceId  --region $us_region_name  --output text`

Availabilityzone=`$describe_vol  --volume-ids $SNAP  --query Volumes[*].AvailabilityZone  --region $us_region_name  --output text`

attachment=`$describe_vol  --volume-ids $SNAP  --query Volumes[*].Attachments[*].Device  --region $us_region_name  --output text`

#instance-name=`$describe_instance --instnce-id $instance_id --query 'Reservations[].Instances[].[Tags[?Key==`Name`]| [0].Value]' --output table`

#instance-name=`\$describe_instance --instance-ids $instance_id --query 'Reservations[].Instances[].[Tags[?Key==`Name`]| [0].Value]' --region $us_region_name  --output text\`

$describe_instance --instance-ids $instance_id --query 'Reservations[].Instances[].[Tags[?Key==`Name`]| [0].Value]' --region $us_region_name  --output text > /tmp/instance-name

ins_name=$(cat /tmp/instance-name)

echo $instance_id

echo $attachment

echo $Availabilityzone

echo $ins_name


vol_name=$ins_name-$attachment:$instance_id


echo $vol_name


SNAP_vol=`$create_snapshot --volume-id $SNAP  --region $us_region_name --output text | awk '{print $3}'`


#SNAP=`$create-snapshot --volume-id $SNAP  --query SnapshotId --region $us_region_name --output text`


aws ec2 create-tags --resources $SNAP_vol --tags Key=Name,Value=$vol_name   --region $us_region_name

aws ec2 create-tags --resources $SNAP_vol --tags Key=Availabilityzone,Value=$Availabilityzone   --region $us_region_name

aws ec2 create-tags --resources $SNAP_vol --tags Key=InstanceID,Value=$instance_id  --region $us_region_name

aws ec2 create-tags --resources $SNAP_vol --tags Key=VolumeID,Value=$SNAP  --region $us_region_name

aws ec2 create-tags --resources $SNAP_vol --tags Key=attachment,Value=$attachment  --region $us_region_name


if [ $? -eq 0 ];

  then

  snap_list+=" $SNAP_vol"


else

  echo "SNAP creation is failed"

fi


done


#Snapshot availability check

for snap in $snap_list;

do

echo $snap

snap_status=`$describe_snapshots --snapshot-ids $snap --query  Snapshots[*].State --region $us_region_name --output text`

while [ "$snap_status" != "completed" ];

  do

    sleep 5

    echo "Test successful"

    snap_status=`$describe_snapshots --snapshot-ids $snap --query  Snapshots[*].State --region $us_region_name --output text`

  done

  $describe_snapshots --snapshot-ids $snap  --query 'Snapshots[*].{Name:Tags[?Key==`Availabilityzone`]|[0].Value}' --region $us_region_name --output text > /tmp/zone

  $describe_snapshots --snapshot-ids $snap  --query 'Snapshots[*].{Name:Tags[?Key==`Name`]|[0].Value}' --region $us_region_name --output text > /tmp/snp_name

  $describe_snapshots --snapshot-ids $snap  --query 'Snapshots[*].{Name:Tags[?Key==`InstanceID`]|[0].Value}' --region $us_region_name --output text > /tmp/InstanceID

  $describe_snapshots --snapshot-ids $snap  --query 'Snapshots[*].{Name:Tags[?Key==`VolumeID`]|[0].Value}' --region $us_region_name --output text > /tmp/VolumeID

  $describe_snapshots --snapshot-ids $snap  --query 'Snapshots[*].{Name:Tags[?Key==`attachment`]|[0].Value}' --region $us_region_name --output text > /tmp/attach

  zone=$(cat /tmp/zone)

  snap_name=$(cat /tmp/snp_name)

  InstanceID=$(cat /tmp/InstanceID)

  VolumeID=$(cat /tmp/VolumeID)

  attachment_deive=$(cat /tmp/attach)


  vol=`$create_volume --volume-type gp3 --snapshot-id $snap --availability-zone $zone  --encrypted --kms-key-id $kms_key --region $us_region_name --output text| awk '{print $10}'`

  aws ec2 create-tags --resources $vol --tags Key=Name,Value=$snap_name  --region $us_region_name

  sleep 5

  $detach_volume --volume-id $VolumeID --region $us_region_name --output text

  sleep 30

  $attach_volume --volume-id $vol --instance-id $InstanceID --device $attachment_deive --region $us_region_name --output text


  if [ $? -eq 0 ];

  then

    echo "snap is available. Replacing the encrypted volume of the instances"


  else

    echo "snap is not available"


fi


done

Note : Server need to be ins stop state to detach the volume . Also you can add one more liner check in the below script to check if instance is online or in stop state . if you  need help please write back i will update the script

 If you need to check the volume which is not encrypted in your account .Please check my other blog. 

Thursday, 25 May 2017

AWS VPC with a NAT Gateway Cloudformation code



{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Description": "A VPC environment in two availability zones with an NAT Gateway.",
  "Parameters": {
    "envPrefix": {
      "Description": "Environment name prefix.",
      "Type": "String",
      "Default": "Test"
    },
    "vpcCidr": {
      "Description": "VPC CIDR block.",
      "Type": "String",
      "Default": "10.60.0.0/22",
      "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
      "ConstraintDescription": "Must be a valid IP CIDR range of the form x.x.x.x/x."
    },
    "publicSubnet1Cidr": {
      "Description": "Public subnet 1 CIDR block.",
      "Type": "String",
      "Default": "10.60.0.0/27",
      "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
      "ConstraintDescription": "Must be a valid IP CIDR range of the form x.x.x.x/x and subnet of VPC."
    },
"publicSubnet2Cidr": {
      "Description": "Public subnet 2 CIDR block.",
      "Type": "String",
      "Default": "10.60.0.32/27",
      "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
      "ConstraintDescription": "Must be a valid IP CIDR range of the form x.x.x.x/x and subnet of VPC."
    },
 
    "publicSubnet3Cidr": {
      "Description": "Public subnet 3 CIDR block.",
      "Type": "String",
      "Default": "10.60.0.64/27",
      "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
      "ConstraintDescription": "Must be a valid IP CIDR range of the form x.x.x.x/x and subnet of VPC."
    },
"publicSubnet4Cidr": {
      "Description": "Public subnet 4 CIDR block.",
      "Type": "String",
      "Default": "10.60.0.96/27",
      "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
      "ConstraintDescription": "Must be a valid IP CIDR range of the form x.x.x.x/x and subnet of VPC."
    },
    "privateSubnet1Cidr": {
      "Description": "Private subnet 1 CIDR block.",
      "Type": "String",
      "Default": "10.60.0.128/27",
      "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
      "ConstraintDescription": "Must be a valid IP CIDR range of the form x.x.x.x/x and subnet of VPC."
    },
"privateSubnet2Cidr": {
      "Description": "Private subnet 2 CIDR block.",
      "Type": "String",
      "Default": "10.60.0.160/27",
      "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
      "ConstraintDescription": "Must be a valid IP CIDR range of the form x.x.x.x/x and subnet of VPC."
    },
"privateSubnet3Cidr": {
      "Description": "Private subnet 3 CIDR block.",
      "Type": "String",
      "Default": "10.60.0.192/27",
      "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
      "ConstraintDescription": "Must be a valid IP CIDR range of the form x.x.x.x/x and subnet of VPC."
    },
"privateSubnet4Cidr": {
      "Description": "Private subnet 4 CIDR block.",
      "Type": "String",
      "Default": "10.60.0.224/27",
      "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
      "ConstraintDescription": "Must be a valid IP CIDR range of the form x.x.x.x/x and subnet of VPC."
    },
"privateSubnet5Cidr": {
      "Description": "Private subnet 5 CIDR block.",
      "Type": "String",
      "Default": "10.60.1.0/27",
      "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
      "ConstraintDescription": "Must be a valid IP CIDR range of the form x.x.x.x/x and subnet of VPC."
    },
"privateSubnet6Cidr": {
      "Description": "Private subnet 6 CIDR block.",
      "Type": "String",
      "Default": "10.60.1.32/27",
      "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
      "ConstraintDescription": "Must be a valid IP CIDR range of the form x.x.x.x/x and subnet of VPC."
    },
"privateSubnet7Cidr": {
      "Description": "Private subnet 7 CIDR block.",
      "Type": "String",
      "Default": "10.60.1.64/27",
      "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
      "ConstraintDescription": "Must be a valid IP CIDR range of the form x.x.x.x/x and subnet of VPC."
    },
"privateSubnet8Cidr": {
      "Description": "Private subnet 8 CIDR block.",
      "Type": "String",
      "Default": "10.60.1.96/27",
      "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
      "ConstraintDescription": "Must be a valid IP CIDR range of the form x.x.x.x/x and subnet of VPC."
    },
"privateSubnet9Cidr": {
      "Description": "Private subnet 9 CIDR block.",
      "Type": "String",
      "Default": "10.60.1.128/27",
      "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
      "ConstraintDescription": "Must be a valid IP CIDR range of the form x.x.x.x/x and subnet of VPC."
    },
"privateSubnet10Cidr": {
      "Description": "Private subnet 10 CIDR block.",
      "Type": "String",
      "Default": "10.60.1.160/27",
      "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
      "ConstraintDescription": "Must be a valid IP CIDR range of the form x.x.x.x/x and subnet of VPC."
    },
"privateSubnet11Cidr": {
      "Description": "Private subnet 11 CIDR block.",
      "Type": "String",
      "Default": "10.60.1.192/27",
      "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
      "ConstraintDescription": "Must be a valid IP CIDR range of the form x.x.x.x/x and subnet of VPC."
    },
"privateSubnet12Cidr": {
      "Description": "Private subnet 12 CIDR block.",
      "Type": "String",
      "Default": "10.60.1.224/27",
      "AllowedPattern": "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
      "ConstraintDescription": "Must be a valid IP CIDR range of the form x.x.x.x/x and subnet of VPC."
    },

    "subnet1AZ": {
      "Description": "Subnet 1 availability zone.",
      "Type": "AWS::EC2::AvailabilityZone::Name"
    },
    "subnet2AZ": {
      "Description": "Subnet 2 availability zone.",
      "Type": "AWS::EC2::AvailabilityZone::Name"
    }
 
   },
 
  "Resources": {
    "vpc": {
      "Type": "AWS::EC2::VPC",
      "Properties": {
        "CidrBlock": {"Ref": "vpcCidr"},
        "InstanceTenancy": "default",
        "EnableDnsSupport": "true",
        "EnableDnsHostnames": "true",
        "Tags": [
          {
            "Key": "Name",
            "Value": {"Fn::Join" : ["-", [{"Ref" : "envPrefix"}, "VPC"]]}
          }
        ]
      }
    },
    "publicSubnet1": {
      "Type": "AWS::EC2::Subnet",
      "DependsOn": ["vpc", "attachGateway"],
      "Properties": {
        "CidrBlock": {"Ref": "publicSubnet1Cidr"},
        "AvailabilityZone": {"Ref" : "subnet1AZ"},
        "VpcId": {"Ref": "vpc"},
        "Tags": [
          {
            "Key": "Name",
            "Value": {"Fn::Join" : ["-", [{"Ref" : "envPrefix"}, "Subnet-Public-1"]]}
          }
        ]
      }
    },
 
    "publicSubnet2": {
      "Type": "AWS::EC2::Subnet",
      "DependsOn": ["vpc", "attachGateway"],
      "Properties": {
        "CidrBlock": {"Ref": "publicSubnet2Cidr"},
        "AvailabilityZone": {"Ref" : "subnet2AZ"},
        "VpcId": {"Ref": "vpc"},
        "Tags": [
          {
            "Key": "Name",
            "Value": {"Fn::Join" : ["-", [{"Ref" : "envPrefix"}, "Subnet-Public-2"]]}
          }
        ]
      }
    },
"publicSubnet3": {
      "Type": "AWS::EC2::Subnet",
      "DependsOn": ["vpc", "attachGateway"],
      "Properties": {
        "CidrBlock": {"Ref": "publicSubnet3Cidr"},
        "AvailabilityZone": {"Ref" : "subnet1AZ"},
        "VpcId": {"Ref": "vpc"},
        "Tags": [
          {
            "Key": "Name",
            "Value": {"Fn::Join" : ["-", [{"Ref" : "envPrefix"}, "Subnet-Public-3"]]}
          }
        ]
      }
    },

"publicSubnet4": {
      "Type": "AWS::EC2::Subnet",
      "DependsOn": ["vpc", "attachGateway"],
      "Properties": {
        "CidrBlock": {"Ref": "publicSubnet4Cidr"},
        "AvailabilityZone": {"Ref" : "subnet2AZ"},
        "VpcId": {"Ref": "vpc"},
        "Tags": [
          {
            "Key": "Name",
            "Value": {"Fn::Join" : ["-", [{"Ref" : "envPrefix"}, "Subnet-Public-4"]]}
          }
        ]
      }
    },

"privateSubnet1": {
      "Type": "AWS::EC2::Subnet",
      "DependsOn": ["vpc", "attachGateway"],
      "Properties": {
        "CidrBlock": {"Ref": "privateSubnet1Cidr"},
        "AvailabilityZone": {"Ref" : "subnet1AZ"},
        "VpcId": {"Ref": "vpc"},
        "Tags": [
          {
            "Key": "Name",
            "Value": {"Fn::Join" : ["-", [{"Ref" : "envPrefix"}, "Subnet-Private-1"]]}
          }
        ]
      }
    },

    "privateSubnet2": {
      "Type": "AWS::EC2::Subnet",
      "DependsOn": ["vpc", "attachGateway"],
      "Properties": {
        "CidrBlock": {"Ref": "privateSubnet2Cidr"},
        "AvailabilityZone": {"Ref" : "subnet2AZ"},
        "VpcId": {"Ref": "vpc"},
        "Tags": [
          {
            "Key": "Name",
            "Value": {"Fn::Join" : ["-", [{"Ref" : "envPrefix"}, "Subnet-Private-2"]]}
          }
        ]
      }
    },

"privateSubnet3": {
      "Type": "AWS::EC2::Subnet",
      "DependsOn": ["vpc", "attachGateway"],
      "Properties": {
        "CidrBlock": {"Ref": "privateSubnet3Cidr"},
        "AvailabilityZone": {"Ref" : "subnet1AZ"},
        "VpcId": {"Ref": "vpc"},
        "Tags": [
          {
            "Key": "Name",
            "Value": {"Fn::Join" : ["-", [{"Ref" : "envPrefix"}, "Subnet-Private-3"]]}
          }
        ]
      }
    },

"privateSubnet4": {
      "Type": "AWS::EC2::Subnet",
      "DependsOn": ["vpc", "attachGateway"],
      "Properties": {
        "CidrBlock": {"Ref": "privateSubnet4Cidr"},
        "AvailabilityZone": {"Ref" : "subnet2AZ"},
        "VpcId": {"Ref": "vpc"},
        "Tags": [
          {
            "Key": "Name",
            "Value": {"Fn::Join" : ["-", [{"Ref" : "envPrefix"}, "Subnet-Private-4"]]}
          }
        ]
      }
    },

"privateSubnet5": {
      "Type": "AWS::EC2::Subnet",
      "DependsOn": ["vpc", "attachGateway"],
      "Properties": {
        "CidrBlock": {"Ref": "privateSubnet5Cidr"},
        "AvailabilityZone": {"Ref" : "subnet1AZ"},
        "VpcId": {"Ref": "vpc"},
        "Tags": [
          {
            "Key": "Name",
            "Value": {"Fn::Join" : ["-", [{"Ref" : "envPrefix"}, "Subnet-Private-5"]]}
          }
        ]
      }
    },

"privateSubnet6": {
      "Type": "AWS::EC2::Subnet",
      "DependsOn": ["vpc", "attachGateway"],
      "Properties": {
        "CidrBlock": {"Ref": "privateSubnet6Cidr"},
        "AvailabilityZone": {"Ref" : "subnet2AZ"},
        "VpcId": {"Ref": "vpc"},
        "Tags": [
          {
            "Key": "Name",
            "Value": {"Fn::Join" : ["-", [{"Ref" : "envPrefix"}, "Subnet-Private-6"]]}
          }
        ]
      }
    },

"privateSubnet7": {
      "Type": "AWS::EC2::Subnet",
      "DependsOn": ["vpc", "attachGateway"],
      "Properties": {
        "CidrBlock": {"Ref": "privateSubnet7Cidr"},
        "AvailabilityZone": {"Ref" : "subnet1AZ"},
        "VpcId": {"Ref": "vpc"},
        "Tags": [
          {
            "Key": "Name",
            "Value": {"Fn::Join" : ["-", [{"Ref" : "envPrefix"}, "Subnet-Private-7"]]}
          }
        ]
      }
    },
"privateSubnet8": {
      "Type": "AWS::EC2::Subnet",
      "DependsOn": ["vpc", "attachGateway"],
      "Properties": {
        "CidrBlock": {"Ref": "privateSubnet8Cidr"},
        "AvailabilityZone": {"Ref" : "subnet2AZ"},
        "VpcId": {"Ref": "vpc"},
        "Tags": [
          {
            "Key": "Name",
            "Value": {"Fn::Join" : ["-", [{"Ref" : "envPrefix"}, "Subnet-Private-8"]]}
          }
        ]
      }
    },

"privateSubnet9": {
      "Type": "AWS::EC2::Subnet",
      "DependsOn": ["vpc", "attachGateway"],
      "Properties": {
        "CidrBlock": {"Ref": "privateSubnet9Cidr"},
        "AvailabilityZone": {"Ref" : "subnet1AZ"},
        "VpcId": {"Ref": "vpc"},
        "Tags": [
          {
            "Key": "Name",
            "Value": {"Fn::Join" : ["-", [{"Ref" : "envPrefix"}, "Subnet-Private-9"]]}
          }
        ]
      }
    },

"privateSubnet10": {
      "Type": "AWS::EC2::Subnet",
      "DependsOn": ["vpc", "attachGateway"],
      "Properties": {
        "CidrBlock": {"Ref": "privateSubnet10Cidr"},
        "AvailabilityZone": {"Ref" : "subnet2AZ"},
        "VpcId": {"Ref": "vpc"},
        "Tags": [
          {
            "Key": "Name",
            "Value": {"Fn::Join" : ["-", [{"Ref" : "envPrefix"}, "Subnet-Private-10"]]}
          }
        ]
      }
    },

"privateSubnet11": {
      "Type": "AWS::EC2::Subnet",
      "DependsOn": ["vpc", "attachGateway"],
      "Properties": {
        "CidrBlock": {"Ref": "privateSubnet11Cidr"},
        "AvailabilityZone": {"Ref" : "subnet1AZ"},
        "VpcId": {"Ref": "vpc"},
        "Tags": [
          {
            "Key": "Name",
            "Value": {"Fn::Join" : ["-", [{"Ref" : "envPrefix"}, "Subnet-Private-11"]]}
          }
        ]
      }
    },

"privateSubnet12": {
      "Type": "AWS::EC2::Subnet",
      "DependsOn": ["vpc", "attachGateway"],
      "Properties": {
        "CidrBlock": {"Ref": "privateSubnet12Cidr"},
        "AvailabilityZone": {"Ref" : "subnet2AZ"},
        "VpcId": {"Ref": "vpc"},
        "Tags": [
          {
            "Key": "Name",
            "Value": {"Fn::Join" : ["-", [{"Ref" : "envPrefix"}, "Subnet-Private-12"]]}
          }
        ]
      }
    },

    "inetGateway": {
      "Type": "AWS::EC2::InternetGateway",
      "DependsOn": ["vpc"],
      "Properties": {
        "Tags": [
          {
            "Key": "Name",
            "Value": {"Fn::Join" : ["-", [{"Ref" : "envPrefix"}, "InternetGateway"]]}
          }
        ]
      }
    },
    "attachGateway": {
      "Type": "AWS::EC2::VPCGatewayAttachment",
      "DependsOn": ["vpc", "inetGateway"],
      "Properties": {
        "VpcId": {"Ref": "vpc"},
        "InternetGatewayId": {"Ref": "inetGateway"}
      }
    },
    "rtbPublic": {
      "Type": "AWS::EC2::RouteTable",
      "DependsOn": ["vpc", "attachGateway"],
      "Properties": {
        "VpcId": {"Ref": "vpc"},
        "Tags": [
          {
            "Key": "Name",
            "Value": {"Fn::Join" : ["-", [{"Ref" : "envPrefix"}, "RTB-Public"]]}
          }
        ]
      }
    },
    "routePublic": {
      "Type": "AWS::EC2::Route",
      "DependsOn": ["rtbPublic"],
      "Properties": {
        "DestinationCidrBlock": "0.0.0.0/0",
        "RouteTableId": {"Ref": "rtbPublic"},
        "GatewayId": {"Ref": "inetGateway"}
      }
 
    },
    "subnetRouteTableAssociationPublic1": {
      "Type": "AWS::EC2::SubnetRouteTableAssociation",
      "DependsOn": ["rtbPublic", "publicSubnet1"],
      "Properties": {
        "RouteTableId": {"Ref": "rtbPublic"},
        "SubnetId": {"Ref": "publicSubnet1"}
      }
    },
    "subnetRouteTableAssociationPublic2": {
      "Type": "AWS::EC2::SubnetRouteTableAssociation",
      "DependsOn": ["rtbPublic", "publicSubnet2"],
      "Properties": {
        "RouteTableId": {"Ref": "rtbPublic"},
        "SubnetId": {"Ref": "publicSubnet2"}
      }
    },
"subnetRouteTableAssociationPublic3": {
      "Type": "AWS::EC2::SubnetRouteTableAssociation",
      "DependsOn": ["rtbPublic", "publicSubnet3"],
      "Properties": {
        "RouteTableId": {"Ref": "rtbPublic"},
        "SubnetId": {"Ref": "publicSubnet3"}
      }
    },
"subnetRouteTableAssociationPublic4": {
      "Type": "AWS::EC2::SubnetRouteTableAssociation",
      "DependsOn": ["rtbPublic", "publicSubnet4"],
      "Properties": {
        "RouteTableId": {"Ref": "rtbPublic"},
        "SubnetId": {"Ref": "publicSubnet4"}
      }
    },
    "rtbPrivate": {
      "Type": "AWS::EC2::RouteTable",
      "DependsOn": ["vpc"],
      "Properties": {
        "VpcId": {"Ref": "vpc"},
        "Tags": [
          {
            "Key": "Name",
            "Value": {"Fn::Join" : ["-", [{"Ref" : "envPrefix"}, "RTB-Private"]]}
          }
        ]
      }
    },
    "subnetRouteTableAssociationPrivate1": {
      "Type": "AWS::EC2::SubnetRouteTableAssociation",
      "DependsOn": ["rtbPublic", "privateSubnet1"],
      "Properties": {
        "RouteTableId": {"Ref": "rtbPrivate"},
        "SubnetId": {"Ref": "privateSubnet1"}
      }
    },
    "subnetRouteTableAssociationPrivate2": {
      "Type": "AWS::EC2::SubnetRouteTableAssociation",
      "DependsOn": ["rtbPublic", "privateSubnet2"],
      "Properties": {
        "RouteTableId": {"Ref": "rtbPrivate"},
        "SubnetId": {"Ref": "privateSubnet2"}
      }
    },
"subnetRouteTableAssociationPrivate3": {
      "Type": "AWS::EC2::SubnetRouteTableAssociation",
      "DependsOn": ["rtbPublic", "privateSubnet3"],
      "Properties": {
        "RouteTableId": {"Ref": "rtbPrivate"},
        "SubnetId": {"Ref": "privateSubnet3"}
      }
    },
"subnetRouteTableAssociationPrivate4": {
      "Type": "AWS::EC2::SubnetRouteTableAssociation",
      "DependsOn": ["rtbPublic", "privateSubnet4"],
      "Properties": {
        "RouteTableId": {"Ref": "rtbPrivate"},
        "SubnetId": {"Ref": "privateSubnet4"}
      }
    },
"subnetRouteTableAssociationPrivate5": {
      "Type": "AWS::EC2::SubnetRouteTableAssociation",
      "DependsOn": ["rtbPublic", "privateSubnet5"],
      "Properties": {
        "RouteTableId": {"Ref": "rtbPrivate"},
        "SubnetId": {"Ref": "privateSubnet5"}
      }
    },
"subnetRouteTableAssociationPrivate6": {
      "Type": "AWS::EC2::SubnetRouteTableAssociation",
      "DependsOn": ["rtbPublic", "privateSubnet6"],
      "Properties": {
        "RouteTableId": {"Ref": "rtbPrivate"},
        "SubnetId": {"Ref": "privateSubnet6"}
      }
    },
"subnetRouteTableAssociationPrivate7": {
      "Type": "AWS::EC2::SubnetRouteTableAssociation",
      "DependsOn": ["rtbPublic", "privateSubnet7"],
      "Properties": {
        "RouteTableId": {"Ref": "rtbPrivate"},
        "SubnetId": {"Ref": "privateSubnet7"}
      }
    },
"subnetRouteTableAssociationPrivate8": {
      "Type": "AWS::EC2::SubnetRouteTableAssociation",
      "DependsOn": ["rtbPublic", "privateSubnet8"],
      "Properties": {
        "RouteTableId": {"Ref": "rtbPrivate"},
        "SubnetId": {"Ref": "privateSubnet8"}
      }
    },
"subnetRouteTableAssociationPrivate9": {
      "Type": "AWS::EC2::SubnetRouteTableAssociation",
      "DependsOn": ["rtbPublic", "privateSubnet9"],
      "Properties": {
        "RouteTableId": {"Ref": "rtbPrivate"},
        "SubnetId": {"Ref": "privateSubnet9"}
      }
    },
"subnetRouteTableAssociationPrivate10": {
      "Type": "AWS::EC2::SubnetRouteTableAssociation",
      "DependsOn": ["rtbPublic", "privateSubnet10"],
      "Properties": {
        "RouteTableId": {"Ref": "rtbPrivate"},
        "SubnetId": {"Ref": "privateSubnet10"}
      }
    },
"subnetRouteTableAssociationPrivate11": {
      "Type": "AWS::EC2::SubnetRouteTableAssociation",
      "DependsOn": ["rtbPublic", "privateSubnet11"],
      "Properties": {
        "RouteTableId": {"Ref": "rtbPrivate"},
        "SubnetId": {"Ref": "privateSubnet11"}
      }
    },
"subnetRouteTableAssociationPrivate12": {
      "Type": "AWS::EC2::SubnetRouteTableAssociation",
      "DependsOn": ["rtbPublic", "privateSubnet12"],
      "Properties": {
        "RouteTableId": {"Ref": "rtbPrivate"},
        "SubnetId": {"Ref": "privateSubnet12"}
      }
    },
    "NAT" : {
  "DependsOn" : "rtbPrivate",
  "Type" : "AWS::EC2::NatGateway",
  "Properties" : {
    "AllocationId" : { "Fn::GetAtt" : ["EIP", "AllocationId"]},
    "SubnetId" : { "Ref" : "publicSubnet1"}
  }
},
"EIP" : {
  "Type" : "AWS::EC2::EIP",
  "Properties" : {
    "Domain" : "vpc"
  }
},
"routePrivate" : {
  "Type" : "AWS::EC2::Route",
  "DependsOn": ["rtbPrivate"],
  "Properties" : {
    "RouteTableId" : { "Ref" : "rtbPrivate" },
    "DestinationCidrBlock" : "0.0.0.0/0",
    "NatGatewayId" : { "Ref" : "NAT" }
  }
}
 

  }

}

Tuesday, 4 October 2016

AWS Volume tagging based on the block device

                                        AWS Volume tagging based on the block device 

#!/usr/bin/env python2


import boto3
REGION = 'ap-southeast-1'
client = boto3.client('ec2',REGION)


#instanceName=''

response = client.describe_volumes()
#response['Volumes'][0]['Attachments'][0]['VolumeId']
for i in response['Volumes']:
    for j in i['Attachments']:
        print "Volume_Id:"+ j['VolumeId']
        volume_id=j['VolumeId']
        print "Instance_Id:"+j['InstanceId']
        instance_id=j['InstanceId']
        print "Device:"+j['Device']
        device=j['Device']
        response = client.describe_instances(
           InstanceIds=[
               instance_id,
           ],
        )

        #print response
        for i in response['Reservations']:
            temp= i['Instances']
            #print temp
            for j in temp:
                #print j['InstanceId']
                for m in j['Tags']:
                    key=m['Key']
                    if (  key == 'Name' ):
                        print"InstanceName:"+ m['Value']+ "\n"
                        #global instanceName
                        instanceName=m['Value']
                   
                        response = client.create_tags(
                            DryRun=False,
                            Resources=[
                                volume_id,
                            ],
                            Tags=[
                                {
                                    'Key': 'Name',
                                    'Value':instanceName + ":" + device
                                },
                            ]
                        )

Create the Security Group rules using python boto API

                           Create the Security Group rules using python boto API
                                             
#!/usr/bin/env python

import boto3
import boto.ec2

#client = boto3.client('ec2',region_name="ap-southeast-1")
ec2 = boto3.resource('ec2',region_name="ap-southeast-1")
vpc = ec2.Vpc("vpc-a65187c3")
security_group = ec2.SecurityGroup('id')

web1 = vpc.create_security_group(
   DryRun=False,
   GroupName='Apache_5',
   Description='testing',
)
web1.authorize_ingress(IpProtocol="tcp",CidrIp="0.0.0.0/0",FromPort=80,ToPort=80)
web1.authorize_ingress(IpProtocol="tcp",CidrIp="0.0.0.0/0",FromPort=20,ToPort=21)
web1.authorize_ingress(IpProtocol="tcp",CidrIp="0.0.0.0/0",FromPort=443,ToPort=443)
web1.authorize_ingress(IpProtocol="tcp",CidrIp="0.0.0.0/0",FromPort=22,ToPort=22)
#web1.authorize_egress(IpProtocol="tcp",CidrIP="0.0.0.0/0",FromPort=443,ToPort=443)
print web1

conn = boto.ec2.connect_to_region("ap-southeast-1")
SG="Apache_5"
groups = conn.get_all_security_groups(filters={'group-name':[SG]})
for group in groups:
   print group.name
   for rule in group.rules:
       print rule.ip_protocol, rule.from_port, rule.to_port, rule.grants

Create VPN connection using python boto API


                                          Create VPN connection using python boto API

#!/usr/bin/env python2

import boto.vpc
import boto.ec2
import time
#boto.set_stream_logger('boto')

#Connect with AWS region

REGION_NAME = 'ap-southeast-1'

#Connect with your Region
conn = boto.vpc.connect_to_region(REGION_NAME)

#Define your VPC

vpc = 'vpc-a6587c3'

#Create Customer Gateway VPN: ipsec vpn tunnel,Customer Gateway IP,BGP ASN NO,for static please specify BGP ASN=65000 ,Else get the BGP ASN NO. from Customer

cg = conn.create_customer_gateway('ipsec.1', '106.51.254.158', 65534)
print cg.id

#Create Virtual Private

vg = conn.create_vpn_gateway('ipsec.1')
print vg.id

#Attaching VPN Gateway with the VPC

vggateway = vg.attach(vpc)

a = type(vggateway)
print a
print vggateway

# Create VPN connection
vpn = conn.create_vpn_connection('ipsec.1',cg.id,vg.id )
#print vpn

Create AWS VPC using python boto

                                 Create AWS VPC using python boto 


#!/usr/bin/env python2

import boto.vpc
import boto.ec2
import time
REGION_NAME = 'ap-southeast-1'

conn = boto.vpc.connect_to_region(REGION_NAME)

# Create a VPC
vpc = conn.create_vpc('10.0.0.0/16')
print vpc

# Configure the VPC to support DNS resolution and hostname assignment
conn.modify_vpc_attribute(vpc.id, enable_dns_support=True)
conn.modify_vpc_attribute(vpc.id, enable_dns_hostnames=True)

# Create an Internet Gateway
gateway = conn.create_internet_gateway()
print gateway

# Attach the Internet Gateway to our VPC
conn.attach_internet_gateway(gateway.id, vpc.id)

# Create a Route Table
route_table = conn.create_route_table(vpc.id)
route_table1 = conn.create_route_table(vpc.id)

print route_table

# Create Subnet - /24 subnet
subnet1 = conn.create_subnet(vpc.id, '10.0.1.0/24',availability_zone='ap-southeast-1a')
subnet2 = conn.create_subnet(vpc.id, '10.0.2.0/24',availability_zone='ap-southeast-1b')
subnet3 = conn.create_subnet(vpc.id, '10.0.3.0/24',availability_zone='ap-southeast-1a')
subnet4 = conn.create_subnet(vpc.id, '10.0.4.0/24',availability_zone='ap-southeast-1b')
subnet5 = conn.create_subnet(vpc.id, '10.0.5.0/24',availability_zone='ap-southeast-1a')
subnet6 = conn.create_subnet(vpc.id, '10.0.6.0/24',availability_zone='ap-southeast-1b')

print subnet1
print subnet2
print subnet3
print subnet4
print subnet5
print subnet6


# Associate Route Table with our public subnet
route1=conn.associate_route_table(route_table.id, subnet1.id)
route2=conn.associate_route_table(route_table.id, subnet2.id)

print route1
print route2

# Associate Route Table with our private subnet
route3=conn.associate_route_table(route_table1.id, subnet3.id)
route4=conn.associate_route_table(route_table1.id, subnet4.id)
route5=conn.associate_route_table(route_table1.id, subnet5.id)
route6=conn.associate_route_table(route_table1.id, subnet6.id)
print route3
print route4
print route5
print route6

# Create a Route from our Internet Gateway to the internet
route = conn.create_route(route_table.id, '0.0.0.0/0', gateway.id)


print route

Configure Redis Cluster on AWS EC2


             Configure a Redis Cluster on Ubuntu 14.04 


Why Redis : 

Redis is an open source (BSD licensed), in-memory data structure store, used as database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs and geospatial indexes with radius queries.

Redis is a NoSQL key-value data store. It can be used as a general purpose cache. keys can be strings, or more complex types (lists, sets, hashes etc).

Prerequisite to configure Redis cluster :

I have used ubuntu 14.04 for my testing .You can use any higher version of ubuntu for your deployment .  

1) Two AWS cloud servers
2) Two Redis Nodes,one master and one slave

Step 1 — Install Redis Master Server

we need to add Chris Lea's Redis repository and perform the ap-get update.Once the repo is added and update process is completed you can install the Radis server. 



Run the following command to update the packages:


Install the Redis server:

Install radis on the master node. 


Follow the same process on the slave node .

Step 2 — Configure Redis Master Server node 

Once redis is installed on the server we need to change few configuration settings on the master node .

Open /etc/redis/redis.conf with your favorite text editor(vim/nano):

#vim /etc/redis/redis.conf

First set a sensible value to the keepalive timer for TCP:
If you want server to be accessible to anyone on the web you need comment out this line  as shown in the above picture:
#bind 127.0.0.1
To protect the Radis from the attacker you must set the password of the radis node .

If you want to take the backup of your radis data you need to uncomment the below lines .


Save your changes .
Restart the Redis service to reload our configuration changes:


Step 3 — Configure Redis Slave node :

Open /etc/redis/redis.conf with your favorite text editor(vim/nano):

#vim /etc/redis/redis.conf


First set a sensible value to the keepalive timer for TCP same as Master node and Make the server accessible to anyone on the web by commenting out the below line :




Set the slave node password to protect it from the unauthorized access: 


we need to Uncomment the masterauth line and provide the password we set up earlier on the master server node: 
                              

Uncomment this line and indicate the IP address where the master server can be reached, followed by the port set on that machine :



Step 4 — Verify the Master-Slave Replication :

Now authenticate with Redis with the password you set when configuring the master:


Promote Slave as Master Cache node :



Rejoin the Slave node to master after the disaster recovery :