Skip to content

Instantly share code, notes, and snippets.

@mabitt
Created January 14, 2022 17:22
Show Gist options
  • Save mabitt/cf900117b5af28de6bca2dcd33c4fe02 to your computer and use it in GitHub Desktop.
Save mabitt/cf900117b5af28de6bca2dcd33c4fe02 to your computer and use it in GitHub Desktop.
Cheatsheet

Cheatsheet collection

AWS cheatsheet

ACM (AWS Certificate Manager)

Get certificate ARN

aws --output text acm list-certificates --query "CertificateSummaryList[?DomainName=='example.com'].[CertificateArn]"

Get certificates remaining days

ARNS=$(aws --output text acm list-certificates --query 'CertificateSummaryList[*].CertificateArn')
for ARN in $ARNS ; do
  DOMAIN=$(aws --output text acm describe-certificate --certificate-arn $ARN --query 'Certificate.DomainName')
  DAYS=$((($(aws --output text acm describe-certificate --certificate-arn $ARN --query 'Certificate.NotAfter' | sed 's/\.\0//')-$(date --utc --date "$1" +%s))/86400))
  echo $DOMAIN $DAYS
done

Cloudfront

Find Distribution ID using Aliases

$ aws cloudfront list-distributions --output text --query "DistributionList.Items[?Aliases.Items[0]=='www.example.net'].{Id:Id}"

Create a new invalidation

SITE=duvidas.example.net
CF_ID=$(aws cloudfront list-distributions --output text --query "DistributionList.Items[?Aliases.Items[0]=='${SITE}'].{Id:Id}")
aws cloudfront create-invalidation --distribution-id ${CF_ID} --paths "/*"

EC2 (Elastic Compute Cloud)

Query Public IP for autoscaling instances

EC2InstancesIP=`aws --output text ec2 describe-instances --filters "Name=tag:Name,Values=name" "Name=instance-state-name,Values=running" --query 'Reservations[*].Instances[*].[PublicIpAddress]'`
if [ -z "$EC2InstancesIP" ] ; then
    echo "No instances alive"
else
    for ec2 in $EC2InstancesIP ; do
        echo "Starting: $ec2"
        <comando>
        echo "Done $ec2"
    done
fi

Query Name/IP using filter

aws --output json ec2 describe-instances --filters "Name=tag:Name,Values=*Name*" --query 'Reservations[*].Instances[*].[InstanceId,Tags[?Key==`Name`].Value[],PrivateIpAddress]'

Query Name/AMI

EC2_Instances=$(aws --output text ec2 describe-instances --filters "Name=instance-state-name,Values=running" --query 'Reservations[*].Instances[*].[InstanceId]')
if [ -z "$EC2_Instances" ] ; then
    echo "No instances alive"
else
    for EC2 in $EC2_Instances ; do
    EC2_AMI=$(aws --output text ec2 describe-instances --query 'Reservations[*].Instances[*].[ImageId]' --instance-ids ${EC2})
    EC2_NAME=$(aws --output text ec2 describe-instances --query 'Reservations[*].Instances[*].[Tags[?Key==`Name`].Value[]]' --instance-ids ${EC2})
    AMI_NAME=$(aws --output text ec2 describe-images --query 'Images[*].[Name]' --image-ids ${EC2_AMI})
    echo "${EC2};${EC2_NAME};${EC2_AMI};${AMI_NAME} "
    done
fi

ELB/ALB

Configure ALB Logging (and deletion protection)

REGION=us-east-1
ELBS=$(aws --region $REGION elbv2 describe-load-balancers --query LoadBalancers[].LoadBalancerArn)
for ELB in $ELBS ; do
 aws --region $REGION elbv2 modify-load-balancer-attributes \
 --load-balancer-arn $ELB \
 --attributes Key=access_logs.s3.enabled,Value=true Key=access_logs.s3.bucket,Value=logging-bucket-$REGION Key=deletion_protection.enabled,Value=true
done

Configure ELB Logging

REGION=us-east-1
ELBS=$(aws --region $REGION elb describe-load-balancers --query LoadBalancerDescriptions[].LoadBalancerName)
for ELB in $ELBS ; do
  aws --region $REGION elb modify-load-balancer-attributes \
  --load-balancer-name $ELB \
  --load-balancer-attributes "{  \"AccessLog\": {\"Enabled\": true,\"S3BucketName\": \"logging-bucket-$REGION\",\"EmitInterval\": 60,\"S3BucketPrefix\": \"\"}}"
done

IAM

List Users, PasswordLastUsed, AccessKeyLastUsed

for name in $(aws --output text iam list-users --query "Users[*].UserName"); do
    printf $name,
    printf $(aws --output text iam get-user --user-name $name --query "User.PasswordLastUsed"),
    for accesskey in $(aws --output text iam list-access-keys --user-name $name --query "AccessKeyMetadata[].AccessKeyId"); do
        printf $(aws --output text iam get-access-key-last-used --access-key-id $accesskey --query "AccessKeyLastUsed.LastUsedDate"),
    done
    printf "\n"
done

List Users in a Group

aws iam get-group --group-name Admin --query "Users[].[UserName,PasswordLastUsed]"

Route53

List domains using tags (must be equal)

aws --output text route53 list-hosted-zones --query "HostedZones[?Config.Comment=='Comment'][Name]"

List domains using tags (using starts_with)

aws --output text route53 list-hosted-zones --query "HostedZones[?Config.Comment!=\`null\`]|[?starts_with(Config.Comment,'Comment')][Name]"

List domains using tags (using contains)

aws --output text route53 list-hosted-zones --query "HostedZones[?Config.Comment!=\`null\`]|[?contains(Config.Comment,'Comment')][Name]"

S3

Configure Server access logging

BUCKETS=$(aws s3api list-buckets --output text --query Buckets[*].Name)
for BUCKET in $BUCKETS ; do
  BUCKET_REGION=$(aws --output text s3api get-bucket-location --bucket $BUCKET)
  if [[ ${BUCKET_REGION} == "sa-east-1" ]] ; then
    aws s3api put-bucket-logging --bucket $BUCKET --bucket-logging-status "{  \"LoggingEnabled\": {  \"TargetBucket\": \"logging-bucket-sae1\",  \"TargetPrefix\": \"S3/$BUCKET/\"  } }"
  else  
    aws s3api put-bucket-logging --bucket $BUCKET --bucket-logging-status "{  \"LoggingEnabled\": {  \"TargetBucket\": \"logging-bucket-use1\",  \"TargetPrefix\": \"S3/$BUCKET/\"  } }"
  fi
done

Terraform cheatsheet

Import Resources

Import RDS instance to module

terraform import "module.rds_module_name.module.db_instance.aws_db_instance.this" rds-instance

Fix replaced resources that can't be removed (OG/PG after major upgrade)

terraform state rm "module.rds_module_name.module.db_option_group.aws_db_option_group.this[0]"
terraform import "module.rds_module_name.module.db_option_group.aws_db_option_group.this[0]" rds-instance-<random id>

Após o import é possivel observar pelo terraform plan que o name_prefix não foi importado corretamente, para corrigir isso é preciso editar manualmente o state. Baixe a versao atual do state (faça uma copia de backup)

terraform state pull > state.json

Busque pela nome do PG/OG a ser corrigido, a variavel name_prefix vai estar com o valor null, substitua pelo nome do prefixo indicado no terraform plan. Aumente o serial em 1 (linha 4), e envie novamente para o s3 usando o comando abaixo.

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