Skip to content

Instantly share code, notes, and snippets.

@Graham-Beer
Created May 15, 2018 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Graham-Beer/7996f5edf9e5fc7a438ae216f0b69fe9 to your computer and use it in GitHub Desktop.
Save Graham-Beer/7996f5edf9e5fc7a438ae216f0b69fe9 to your computer and use it in GitHub Desktop.
class AwsInstance {
[String] $TagName
[String] $InstanceId
[String] $Status
Hidden [Object] $EC2Instance
AwsInstance([String]$name) {
if ($name -match '^i-[a-f0-9]+$') {
$this.InstanceId = $name
$this.EC2Instance = $this.getInstanceFromInstanceId($name)
$this.TagName = ($this.EC2Instance.RunningInstance.Tag).Where({ $_.key -eq 'Name' }).Value
}
else {
$this.EC2Instance = $this.getInstanceFromTagName($name)
$this.TagName = $name
$this.InstanceId = $this.EC2Instance.RunningInstance.InstanceId
}
$this.GetStatus()
}
[Amazon.EC2.Model.Reservation] getInstanceFromTagName([String]$name) {
$Filter1 = [Amazon.EC2.Model.Filter]::new("key", ('Name', 'name'))
$Filter2 = [Amazon.EC2.Model.Filter]::new('value', $name)
$ResourceId = (Get-EC2Tag -Filter @($filter1, $filter2)).Where({$_.ResourceType -eq 'instance'})
return Get-EC2Instance -InstanceId $ResourceId.ResourceId
}
[Amazon.EC2.Model.Reservation] getInstanceFromInstanceId([String]$name) {
return Get-EC2Instance -InstanceId $name
}
[Void] Start() {
try {
$this.EC2Instance | Start-EC2Instance
$this.GetStatus()
}
catch {
$this.Status = $_.Exception.Message
}
}
[Void] Restart() {
try {
$this.EC2Instance | Restart-EC2Instance
$this.GetStatus()
}
catch {
$this.Status = $_.Exception.Message
}
}
[Void] Stop() {
try {
$this.EC2Instance | Stop-EC2Instance
$this.GetStatus()
}
catch {
$this.Status = $_.Exception.Message
}
}
[Void] GetStatus() {
try {
$this.Status = ($this.EC2Instance | Get-EC2InstanceStatus).InstanceState.Name.Value
}
catch {
$this.Status = $_.Exception.Message
}
}
Hidden [Void] getInstance() {
$this.EC2Instance = Get-EC2Instance -InstanceId $this.InstanceId
}
static [String] Start([String]$name) {
$instance = [AwsInstance]::new($name)
$instance.Start()
return "Status: " + $instance.Status
}
static [String] Stop([String]$name) {
$instance = [AwsInstance]::new($name)
$instance.Stop()
return "Status: " + $(if (-not $instance.Status) { "Stopped" })
}
static [String] Restart([String]$name) {
$instance = [AwsInstance]::new($name)
$instance.Restart()
return "Status: " + $instance.Status
}
static [AwsInstance] GetStatus([String]$name) {
$instance = [AwsInstance]::new($name)
$instance.GetStatus()
return $instance
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment