Skip to content

Instantly share code, notes, and snippets.

@reschenburgIDBS
Last active October 30, 2020 11:46
Show Gist options
  • Save reschenburgIDBS/3e6e404af459fdb75debb534ef2647a8 to your computer and use it in GitHub Desktop.
Save reschenburgIDBS/3e6e404af459fdb75debb534ef2647a8 to your computer and use it in GitHub Desktop.
terraform Global Accelerator Security Group in VPC workaround with assume role support - requires jq installed on the terraforming device!!
resource "aws_vpc" "vpc" {
cidr_block = "10.0.0.0/16"
tags = {
Name = "test-vpc"
}
provisioner "local-exec" {
when = destroy
command = <<EOT
if [[ "${var.aws_role_arn}" != "" ]]; then
TEMPSESSION=$(aws sts assume-role --role-arn ${var.aws_role_arn} --role-session-name destroy-ga-sg)
export AWS_ACCESS_KEY_ID=$(echo $TEMPSESSION | jq -r .Credentials.AccessKeyId)
export AWS_SECRET_ACCESS_KEY=$(echo $TEMPSESSION | jq -r .Credentials.SecretAccessKey)
export AWS_SESSION_TOKEN=$(echo $TEMPSESSION | jq -r .Credentials.SessionToken)
fi
GA_SG=$(aws ec2 describe-security-groups --region ${var.region} --filters Name=vpc-id,Values=${self.id} Name=group-name,Values='GlobalAccelerator' --query 'SecurityGroups[*].[GroupId]' --output text)
if [[ $GA_SG != "" ]]; then
echo "Found a GA SG: $GS_SG - deleting it."
aws ec2 delete-security-group --group-id $GA_SG --region ${var.region}
fi
EOT
}
}
@mgiardiidbs
Copy link

terraform 0.13 compatible

resource "aws_vpc" "vpc" {
  cidr_block = "10.0.0.0/16"

  tags = {
    Name = "test-vpc"
  }  
}

resource "null_resource" "ga_security_grup" {
  triggers = {
    aws_role_arn = var.aws_role_arn
    region       = var.region
    aws_vpc      = aws_vpc.vpc.id
  }

  provisioner "local-exec" {
    when    = destroy
    command = <<EOT
      if [[ "${self.triggers.aws_role_arn}" != "" ]]; then
        TEMPSESSION=$(aws sts assume-role --role-arn ${self.triggers.aws_role_arn} --role-session-name destroy-ga-sg)
        export AWS_ACCESS_KEY_ID=$(echo $TEMPSESSION | jq -r .Credentials.AccessKeyId)
        export AWS_SECRET_ACCESS_KEY=$(echo $TEMPSESSION | jq -r .Credentials.SecretAccessKey)
        export AWS_SESSION_TOKEN=$(echo $TEMPSESSION | jq -r .Credentials.SessionToken)
      fi
      GA_SG=$(aws ec2 describe-security-groups --region ${self.triggers.region} --filters Name=vpc-id,Values=${self.triggers.aws_vpc} Name=group-name,Values='GlobalAccelerator' --query 'SecurityGroups[*].[GroupId]' --output text)
      if [[ $GA_SG != "" ]]; then
        echo "Found a GA SG: $GS_SG - deleting it."
        aws ec2 delete-security-group --group-id $GA_SG --region ${self.triggers.region}
      fi
    EOT
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment