AWS PowerShell

From open-voip.org

Jump to: navigation, search

Contents

dowvload AWS cli tools foe windows

http://sdk-for-net.amazonwebservices.com/latest/AWSToolsAndSDKForNet.msi

Install AWS PowerShell

run the powershell ISE

powershell_ise.exe
Set-ExecutionPolicy RemoteSigned
Import-Module "C:\Program Files (x86)\AWS Tools\PowerShell\AWSPowerShell\AWSPowerShell.psd1"

verify by

 Get-Module

basics

search for a command

Get-Command -Noun ec2*
Get-Command -verb new -Noun ec* 

help on a command with examples:

help NewEC2Instance -Examples

help on a command parameter:

help Get-EC2Instance -Parameter filter
Get-History

latest aws command with the response:

$AWSHistory
$AWSHistory.commands
$AWSHistory.commands.LastServiceResponse

run command from history

Invoke-History 11

Profile, Region and Cerdentials

store credentials to a profile

set-AWSCredentials -StoreAs AWSAMOS -Accesskey <my_Key> - SecretKey <my_key>

Init the profile

Initialize-AWSDefaults -ProfileName AWSAMOS -Region us-west-1

set the default region to a profile

 Initialize-AWSDefaults -ProfileName AWSAmos -Region us-west-2

set the default region

Set-DefaultAWSRegion 

or clear

ClearDefaultAWSRegion

get all regions

Get-AWSRegion

list of loaded modules to powershel:

Get-Module -ListAvailable aw*

functions

(get-command Get-Tnet-RDS).Definition

AMI and Instance

List of AMI

Get-Ec2Image
get EC2ImageByName

Start a new instance

New-EC2Instance -ImageId ami-7527031c -MinCount 1 -MaxCount 1 -KeyName myPSKeyPair -SecurityGroups myPSSecurityGroup -InstanceType t1.micro

to get the Instance ID to a parameter:

$i = New-EC2Instance -ImageId ami-7527031c -MinCount 1 -MaxCount 1 -KeyName myPSKeyPair -SecurityGroups myPSSecurityGroup -InstanceType t1.micro | select -ExpandProperty instances

display the instance info:

$i
$.InstanceID

Security Group

get the first security group to a variable

$sg = Get-Ec2SecurityGroup | select -First 1

add rule to security group in $sg:

$ip = New-Object Amazon.EC2.Model.IpPermission
$ip.FromPort = 3389 
$ip.IpProtocol = 'tcp'
$ip.IpRanges.add('0.0.0.0/0')
$ip
grant-EC2SecurityGroupIngress -GrouId $sg.GroupId -IpPermissions $ip

add a security group

$sg2 = New-EC2SecurityGroup -GroupName myPSSecurityGroup -GroupDescription "EC2-Classic from PowerShell"

Tags

New-EC2Tag -Resources $1.InstanceId -Tags @{key='name';value='Server2'},@{key='name2';value='Server2'}

Search using tags

Get-EC2Instance -Filter @{name='tag:Name';values='Server2'}

powershell on remote windows instance

get instance metadata or user data

Invoke-RestMethod http://169.254.169.254/latest/meta-data/ami-id

add EBS

$vol = New-Object Amazon.EC2.Model.EbsBlockDevice
$vol.VolumeSize = 100
$vol.volumeType = 'gp2'
$map = New-Object Amazon.EC2.Model.BlockDeviceMapping 
$map
$map.DeviceName = 'xvdf'
$map.EBS = $vol

EXAMPLES

 Get-EC2InstanceAttribute -InstanceId i-79a09c9c -Attribute instanceType |  Where-Object {($_.InstanceType -eq 'c3.2xlarge')}

List of Instances in VPC

$Instances = (Get-EC2Instance).instances
$VPCS = Get-EC2Vpc
foreach ($VPC in $VPCS) {
     $Instances | Where-Object {$_.VpcId -eq $VPC.VpcId} | foreach {
        New-Object -TypeName PSObject -Property @{
            'VpcId' = $_.VpcId
            'VPCName' = ($VPC.Tags | Where-Object {$_.Key -eq 'Name'}).Value
            'InstanceId' = $_.InstanceId
            'InstanceName' = ($_.Tags | Where-Object {$_.Key -eq 'Name'}).Value
            'LaunchTime' = $_.LaunchTime
            'State' = $_.State.Name
            'Type' = $_.InstanceType
            'Private IP' = $_.PrivateIpAddress
            'Public IP' = $_.PublicIpAddress
            'SG' = $_.SecurityGroups
            'Subnet' = $_.SubnetId
            'Tags' = $_.tag
        }
    }
}

list all ips of Prod (tag) instances

$Instances = (Get-EC2Instance -Filter @( @{name='tag:Type'; values="PROD"})).instances
$VPCS = Get-EC2Vpc
foreach ($VPC in $VPCS) {
     $Instances | Where-Object {$_.VpcId -eq $VPC.VpcId} | foreach {
        New-Object -TypeName PSObject -Property @{
            'Private IP' = $_.PrivateIpAddress
        }
    }
}

list all running or stopped instances

you can change "stopped" to "running"

$StoppedInstances = (Get-EC2Instance).instances | Where-Object {$_.State.Name -eq "stopped"}
$VPCS = Get-EC2Vpc
foreach ($VPC in $VPCS) {
    $StoppedInstances | Where-Object {$_.VpcId -eq $VPC.VpcId} | foreach {
       New-Object -TypeName PSObject -Property @{
           'InstanceId' = $_.InstanceId
           'InstanceName' = ($_.Tags | Where-Object {$_.Key -eq 'Name'}).Value
           'LaunchTime' = $_.LaunchTime
           'State' = $_.State.Name
           'Private IP' = $_.PrivateIpAddress
 
       } | Format-Table -HideTableHeaders 
   }
}

list all instances with thier tags

$Instances = (Get-EC2Instance).instances
$VPCS = Get-EC2Vpc
foreach ($VPC in $VPCS) {
     $Instances | Where-Object {$_.VpcId -eq $VPC.VpcId} | foreach {
        New-Object -TypeName PSObject -Property @{
            'InstanceId' = $_.InstanceId
            'InstanceName' = ($_.Tags | Where-Object {$_.Key -eq 'Name'}).Value
            'Client' = ($_.Tags | Where-Object {$_.Key -eq 'Client'}).Value
            'BAckup' = ($_.Tags | Where-Object {$_.Key -eq 'Backup'}).Value
            'Type' = ($_.Tags | Where-Object {$_.Key -eq 'Type'}).Value
        }
    }
}

save object of stopped instances to a file

$StoppedInstances = (Get-EC2Instance).instances | Where-Object {$_.State.Name -eq "stopped"}  | Export-Clixml "C:\Users\amoss\OneDrive - TradAir\Powershell\myfiles\stoppedInstances.xml"

import object of stopped instances from a file

 $StoppedInstances = Import-Clixml "C:\Users\amoss\OneDrive - TradAir\Powershell\myfiles\stoppedInstances.xml"

list of servers in a table view

PS C:\WINDOWS\system32> $Instances = (Get-EC2Instance).instances 
$VPCS = Get-EC2Vpc
foreach ($VPC in $VPCS) {
     $Instances | Where-Object {$_.VpcId -eq $VPC.VpcId} | foreach {
        New-Object -TypeName PSObject -Property @{
            'InstancType' = $_.InstanceType 
            'InstancState' = $_.State.Name
            'InstanceName' = ($_.Tags | Where-Object {$_.Key -eq 'Name'}).Value
            'Client' = ($_.Tags | Where-Object {$_.Key -eq 'Client'}).Value
            'BAckup' = ($_.Tags | Where-Object {$_.Key -eq 'Backup'}).Value
            'Type' = ($_.Tags | Where-Object {$_.Key -eq 'Type'}).Value
        } | Format-Table -HideTableHeaders  
    }
}

list instances from all regions - comma seperated

$Regions = Get-AWSRegion $ctr = 0 foreach ($Region in $Regions) {

   $Instances = (Get-EC2Instance -Region $Region.Region).instances 
   $Instances | foreach {
      New-Object -TypeName PSObject -Property @{
          'ctr' = $ctr
          'Region' = $Region.Region + ","
          'platform' = ($_.Platform).Value+ ","
          'AZ' = $_.Placement.AvailabilityZone + ","
          'InstanceName' = ($_.Tags | Where-Object {$_.Key -eq 'Name'}).Value + ","
          'InstancType' = $_.InstanceType.Value + "," 
          'Client' = ($_.Tags | Where-Object {$_.Key -eq 'Client'}).Value + ","
          'Type' = ($_.Tags | Where-Object {$_.Key -eq 'Type'}).Value + "," 
          'PrivateIP' = ($_.PrivateIpAddress) + ","
          'PublicIP' = ($_.PublicIpAddress) + ","
      } | Format-Table -HideTableHeaders 
            $ctr=$ctr+1
  } }

list on instances filter by TAG

 Get-EC2Instance -Filter @( @{name='tag:Type'; values="System"}) | Select-Object -ExpandProperty Instances

Route53 - Get records paging

PS C:\WINDOWS\system32> $rs=Get-R53ResourceRecordSet -HostedZoneId /hostedzone/Z295CSUXYNZ5HQ

   while ($rs.IsTruncated -eq $true) {
       echo   $rs
       Get-R53ResourceRecordSet -HostedZoneId /hostedzone/Z295CSUXYNZ5HQ -StartRecordName $rs.NextRecordName | Select -ExpandProperty ResourceRecordSets | measure
       $rs=Get-R53ResourceRecordSet -HostedZoneId /hostedzone/Z295CSUXYNZ5HQ -StartRecordName $rs.NextRecordName
   } 

Route53 - Get all records (even if there are more than 100)

   $rs=Get-R53ResourceRecordSet -HostedZoneId /hostedzone/Z295CSUXYNZ5HQ 
   while ($rs.IsTruncated -eq $true) {
       Get-R53ResourceRecordSet -HostedZoneId /hostedzone/Z295CSUXYNZ5HQ -StartRecordName $rs.NextRecordName | Select -ExpandProperty ResourceRecordSets 
       $rs=Get-R53ResourceRecordSet -HostedZoneId /hostedzone/Z295CSUXYNZ5HQ -StartRecordName $rs.NextRecordName
   }

list all RDS with their tags

change the account name XXXXXX

$Instances = (Get-RDSDBInstance)
    $Instances | foreach {
       New-Object -TypeName PSObject -Property @{
           'InstancType' = $_.DBInstanceClass 
           'ResourceID' = $_.DbiResourceId
           'StorageType' = $_.StorageType
           'StorageSize' = $_.AllocatedStorage  
           'Type' = (Get-RDSTagForResource -ResourceName "arn:aws:rds:eu-west-1:XXXXXX:db:$($_.DBInstanceIdentifier)" | Where-Object {$_.Key -eq 'Type'} ).Value 
           'Client' = (Get-RDSTagForResource -ResourceName "arn:aws:rds:eu-west-1:XXXXXX:db:$($_.DBInstanceIdentifier)" | Where-Object {$_.Key -eq 'Client'} ).Value 
           'env' = (Get-RDSTagForResource -ResourceName "arn:aws:rds:eu-west-1:XXXXXX:db:$($_.DBInstanceIdentifier)" | Where-Object {$_.Key -eq 'env'} ).Value 
   } | Format-Table -HideTableHeaders  
}

get RDS with Tags from all regions

$Regions = Get-AWSRegion
foreach ($Region in $Regions) {
   
    $Instances = (Get-RDSDBInstance -Region $Region.Region)
    $Instances | foreach {
       New-Object -TypeName PSObject -Property @{
           'DB-Name' = $_.DBInstanceIdentifier.ToString() + ","
          'InstancType' = $_.DBInstanceClass.ToString() + ","
          'StorageType' = $_.StorageType.ToString()+ ","
          'StorageSize' = $_.AllocatedStorage.ToString()  + ","
          'Type' = (Get-RDSTagForResource  -Region $Region.Region -ResourceName "arn:aws:rds:$($Region):XXXXXXX:db:$($_.DBInstanceIdentifier)" | Where-Object {$_.Key -eq 'Type'} ).Value + ","
          'Client' = (Get-RDSTagForResource   -Region $Region.Region -ResourceName "arn:aws:rds:$($Region):XXXXXXXXX:db:$($_.DBInstanceIdentifier)" | Where-Object {$_.Key -eq 'Client'} ).Value + ","
          'env' = (Get-RDSTagForResource   -Region $Region.Region -ResourceName "arn:aws:rds:$($Region):XXXXXXXXX:db:$($_.DBInstanceIdentifier)" | Where-Object {$_.Key -eq 'env'} ).Value + "," 
          'Regoin' = $Region.ToString() + ","
       } | Format-Table -HideTableHeaders 
   } 

}

list of all records,type and IPs - even if there are more than 100

$rs = Get-R53ResourceRecordSet -HostedZoneId /hostedzone/Z295CSUXYNZ5HQ
$ctr = 0
while ($rs.IsTruncated -eq $true) {
  $rs.ResourceRecordSets | ForEach-Object { 
    New-Object -TypeName PSObject -Property @{
      'name'=$_.Name
      'TTL'=$_.TTL
      'Type'=$_.Type
      'value' =  $_.ResourceRecords | ForEach-Object {
        New-Object -TypeName PSObject -Property @{
        'value' = $_.value
        'ctr' = $ctr
       }
       $ctr=$ctr+1
      }
     }
   } 
   $rs=Get-R53ResourceRecordSet -HostedZoneId /hostedzone/Z295CSUXYNZ5HQ -StartRecordName $rs.NextRecordName
 }

list all EIP - Elastic IPs

$EIPs = Get-EC2Address
     $EIPs | foreach {
        New-Object -TypeName PSObject -Property @{
            'Elastic IP' = $_.PublicIp
    }
}

list of volumes and Tags

$Regions = Get-AWSRegion
 foreach ($Region in $Regions) {
  $Volumes = (Get-EC2Volume -Region $Region.Region)
    $Volumes | foreach {
    New-Object -TypeName PSObject -Property @{
           'The instance client tag that attached to this volume' = (((Get-EC2Instance -I ($_.Attachment)[0].InstanceId -Region $Region.Region).Instances[0]).Tags | Where-Object {$_.Key -eq 'Client'}).Value + ","
          'Attachment_instance' = ($_.Attachment)[0].InstanceId + ","
          'Attachment_volume' = ($_.Attachment)[0].VolumeId + ","
          'VolumeID' = ($_.VolumeId).ToString() + ","
          'tags' = ($_.Tags)
      } | Format-Table  
  } }

set CLIENT tag value of an instance to its volumes

   $Regions = Get-AWSRegion
 foreach ($Region in $Regions) {
  $Volumes = (Get-EC2Volume -Region $Region.Region)
    $Volumes | foreach      {  
             $tag = New-Object Amazon.EC2.Model.Tag
             $tag.Key = "Client"
             $tag.Value = (((Get-EC2Instance -I ($_.Attachment)[0].InstanceId -Region $Region.Region).Instances[0]).Tags | Where-Object {$_.Key -eq 'Client'}).Value
              New-EC2Tag -Resource ($_.Attachment)[0].VolumeId -Tag $tag -AccessKey XXXXXXXXXX -SecretKey XXXXXXX -Region $Region.Region   
             "New-EC2Tag -Resource " + ($_.Attachment)[0].VolumeId + " -Tag " + $tag + " -AccessKey XXXXXXX-SecretKey XXXXXXXXXXX-Region " + $Region.Region   
    } 
  }

install and use ssh

install

iex (New-Object Net.WebClient).DownloadString("https://gist.github.com/darkoperator/6152630/raw/c67de4f7cd780ba367cccbc2593f38d18ce6df89/instposhsshdev")

create ssh session

New-SSHSession -ComputerName "10.2.1.86" -Credential (Get-Credential root)

get sessions

Get-SSHSession

get trusted servers

Get-SSHTrustedHost

remove session

Remove-SSHSession -Index 0 -Verbose

run command by session

Invoke-SSHCommand -Index 0 -Command "uname -a"

Get Instances costs / price

# get the prices from AWS  URL
Invoke-WebRequest -Uri  https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonEC2/current/index.csv -OutFile  C:\amos\EC2_products.csv
# Remove first 5 Lines
 (Get-Content C:\amos\EC2_products.csv | Select-Object -Skip 5) | Set-Content C:\amos\EC2_products.csv -Force
#load the csv file
 $EC2_products = Import-Csv C:\amos\EC2_products.csv
# display the costs
$EC2_products | Where-Object {$_."Instance Type" -eq "m1.large" -and $_.PurchaseOption -eq "" -and $_.Location -like "*Ireland*"}| foreach           {
      New-Object -TypeName PSObject -Property @{
          'Unit' = $_.Unit
          'TermType' = $_.TermType
          'PricePerUnit' = $_.PricePerUnit
          'Currency' = $_.Currency
          'PurchaseOption' = $_.PurchaseOption
          'Instance Type' = $_."Instance Type"
          'Location' = $_.Location
      } | Format-Table -HideTableHeaders 
      }

Get RDS costs/ price

# get the prices from AWS  URL 
Invoke-WebRequest -Uri  https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonRDS/current/index.csv -OutFile  C:\amos\RDS_products.csv
# Remove first 5 Lines
 (Get-Content C:\amos\RDS_products.csv | Select-Object -Skip 5) | Set-Content C:\amos\RDS_products.csv -Force
#load the csv file
 $RDS_products = Import-Csv C:\amos\RDS_products.csv
# display the costs
 $RDS_products | Where-Object { $_."Database Engine" -eq "MySQL" -and $_.PurchaseOption -eq "" -and $_.Location -like "*Ireland*"}| foreach  {
      New-Object -TypeName PSObject -Property @{
          'Unit' = $_.Unit
          'TermType' = $_.TermType
          'PricePerUnit' = $_.PricePerUnit
          'Currency' = $_.Currency
          'PurchaseOption' = $_.PurchaseOption
          'Instance Type' = $_."Instance Type"
          'Location' = $_.Location
      } | Format-Table -HideTableHeaders 
      }

run ssh and command on remote linux using function

function Get-Tnet-RDS
{
 param( [string]$TnetIP,[string]$UserName,[string]$Password )
 $secpasswd = ConvertTo-SecureString "$Password" -AsPlainText -Force
 $creds = New-Object System.Management.Automation.PSCredential ("$UserName", $secpasswd)
 $Session = (New-SSHSession -ComputerName "$TnetIP" -Credential $creds).SessionId
 (Invoke-SSHCommand -Index $Session -Command "grep --only-matching --perl-regex ""(?<=toip\=).*to"" /etc/config/Config.xml | awk -F' ' '{print `$1}'").Output
 Remove-SSHSession -Index $Session
}

Run it

Get-Tnet-RDS -TnetIP "10.0.0.12" -UserName "root" -Password "XXXXXXX"

run tcping

function TCPING {

 param( [string]$DestIP,[string]$DestPort	 )
 $tcping_stat_line = C:\tcptrace\tcping.exe "$DestIP" "$DestPort" | Select-String Minimum
 $tcping_stat_line = $tcping_stat_line.ToString()
 $tcping_stat_line
 $min_val = $min_val.ToString()
 $min_val=(($tcping_stat_line.Split(",")[0]).ToString()).Split("=")[1].Replace("ms","").Trim()
 $max_val=(($tcping_stat_line.Split(",")[1]).ToString()).Split("=")[1].Replace("ms","").Trim()
 $avg_val=(($tcping_stat_line.Split(",")[2]).ToString()).Split("=")[1].Replace("ms","").Trim()
 "min = ", $min_val
 "max = ", $max_val
 "avg = ", $avg_val

}

powershell tcping script for PRTG

 $min_val = $null
 $tcping_output =  C:\tcptrace\tcping.exe "8.8.8.8" "80" | Select-String -Pattern "Mini",faile
 $tcping_stat_line = $tcping_output | Select-String Minimum
 $tcping_failed = $tcping_output | Select-String faile
 $tcping_failed = $tcping_failed.ToString() 
 if ($tcping_stat_line){
   $tcping_stat_line = $tcping_stat_line.ToString()
 }
 if ($min_val){
   $min_val=((($tcping_stat_line.Split(",")[1]).ToString()).Split("=")[1].Replace("ms","").Trim()).ToString()
 }
 $tcping_failed  = ((($tcping_failed.Split(",")[1]).ToString()).Split("failed")[0].Trim()).ToString()
 if ($tcping_failed -eq 0) {
   $x=[string]$min_val+":OK"
   write-host $x
   #  exit 0
 }
 else {
   $x=[string]$min_val+":TCPING Failed"
   write-host $x
   #  exit 2
 }
Personal tools