Skip to content

Instantly share code, notes, and snippets.

@kenfdev
Last active December 20, 2021 05:08
Show Gist options
  • Save kenfdev/eae340e19b6bde38ae0d6a698a180e88 to your computer and use it in GitHub Desktop.
Save kenfdev/eae340e19b6bde38ae0d6a698a180e88 to your computer and use it in GitHub Desktop.
AWS

API Gateway

Lambda Permission for API Gateway in Terraform

  resource "aws_api_gateway_rest_api" "MyDemoAPI" {
  name        = "MyDemoAPI"
  description = "This is my API for demonstration purposes"
  }
    
  resource "aws_lambda_permission" "lambda_permission" {
  statement_id  = "AllowMyDemoAPIInvoke"
  action        = "lambda:InvokeFunction"
  function_name = "MyDemoFunction"
  principal     = "apigateway.amazonaws.com"
- The / */* /* part allows invocation from any stage, method and resource path
- within API Gateway REST API.
  source_arn = "${aws_api_gateway_rest_api.MyDemoAPI.execution_arn}/ */* /*"
  }
[CmdletBinding()]
param (
[Parameter()]
[string]
$AwsProfile = 'default',
[Parameter()]
[string]
$TargetHost = '',
[Parameter()]
[string]
$TargetPort = '22'
)
# Configuration
# Change these values to reflect your environment
$awsRegion = 'ap-northeast-1'
$maxIteration = 10
$sleepDuration = 10
$currentStatus = (aws ssm describe-instance-information --filters "Key=InstanceIds,Values=$TargetHost" --output text --query 'InstanceInformationList[0].PingStatus' --profile $AwsProfile --region $awsRegion)
Write-Host "Instance status: $currentStatus"
if ($currentStatus -eq "Online" ) {
aws ssm start-session --target $TargetHost --document-name AWS-StartSSHSession --parameters portNumber=$TargetPort --profile $AwsProfile --region $awsRegion
exit 0
}
# Instance is offline - start the instance
Write-Host "Instance is offline. Starting instance..."
aws ec2 start-instances --instance-ids $TargetHost --profile $AwsProfile --region $awsRegion
for ($count = 0; $count -lt $maxIteration; $count++) {
Write-Host "Waiting for instance to start...$($count + 1)/$maxIteration"
Start-Sleep -Seconds $sleepDuration
$currentStatus = (aws ssm describe-instance-information --filters "Key=InstanceIds,Values=$TargetHost" --output text --query 'InstanceInformationList[0].PingStatus' --profile $AwsProfile --region $awsRegion)
if ($currentStatus -eq "Online" ) {
break
}
}
if ($currentStatus -ne "Online") {
Write-Host "Failed to start the instance..."
exit 1
}
# If the instance is online, start the session
Write-Host "The instance is online. Starting session..."
aws ssm start-session --target $TargetHost --document-name AWS-StartSSHSession --parameters portNumber=$TargetPort --profile $AwsProfile --region $awsRegion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment