AWS CLI


사용법

  1. –filters의 경우 공식문서에 지원하는 filter명이 있음.

iam

aws sts get-caller-identity

# Assume Role
aws sts assume-role --role-arn arn --role-session-name role-session-name --region ap-northeast-2

ASSUME_ROLE_CREDENTIALS=$(aws sts assume-role --role-arn arn --role-session-name role-session-name --region ap-northeast-2)
export AWS_ACCESS_KEY_ID=$(echo $ASSUME_ROLE_CREDENTIALS | jq .Credentials.AccessKeyId | sed 's/"//g')
export AWS_SECRET_ACCESS_KEY=$(echo $ASSUME_ROLE_CREDENTIALS | jq .Credentials.SecretAccessKey | sed 's/"//g')
export AWS_SESSION_TOKEN=$(echo $ASSUME_ROLE_CREDENTIALS | jq .Credentials.SessionToken | sed 's/"//g')
unset AWS_ACCESS_KEY_ID
unset AWS_SECRET_ACCESS_KEY
unset AWS_SESSION_TOKEN

# Assume Role with WebIdentity
aws sts assume-role-with-web-identity --role-arn arn:aws:iam::558846430793:role/PythonTestRole --role-session-name role-session-name --web-identity-token eyJhbGciOiJSUzI1NiIsImtpZCI6ImU0NjQ2MzIwZjA4Yjk5MmU3MGMyNzA5ZDYyZTg1MDM0ZWY4MmNkZTcifQ.eyJhdWQiOlsic3RzLmFtYXpvbmF3cy5jb20iXSwiZXhwIjoxNzAwNTU2OTY1LCJpYXQiOjE3MDA0NzA1NjUsImlzcyI6Imh0dHBzOi8vb2lkYy5la3MuYXAtbm9ydGhlYXN0LTIuYW1hem9uYXdzLmNvbS9pZC9BODg0NUQzRjBFNUMzODUyMjcyMDREMzNCODYzNUFCQyIsImt1YmVybmV0ZXMuaW8iOnsibmFtZXNwYWNlIjoicHl0aG9uIiwicG9kIjp7Im5hbWUiOiJweXRob24tdGVzdC01OGQ0ODVmYjQtN3g0NDgiLCJ1aWQiOiJjMTY0ZjJmMi1hOTA5LTRlNzEtYjJkYi04OGYxZGE4MjY2YTUifSwic2VydmljZWFjY291bnQiOnsibmFtZSI6InB5dGhvbi10ZXN0LXNhIiwidWlkIjoiMjlmN2I3NzctNWUwMS00YWNlLWI2MTMtMTEzNWI2ZTVhNjViIn19LCJuYmYiOjE3MDA0NzA1NjUsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDpweXRob246cHl0aG9uLXRlc3Qtc2EifQ.Rfvhoaqm81TxygqEDm751XrVhXfE95xIyGIstcb2WpWwSusMju5ZXBmh4vr2wJtscvcY5AZffy6sOQUKPixJxuOIqd-qm_GGlBzNL4ceBRq7AFhjSepG-NW112yCXmsRCJJMf7e9m6v0mc5I6skZYv8zTLHFfH4Ii30EBUZOk7qkPp6tDJy5tEBJahxAZefqYz4fw9UQbrBgdsJRSSS_fTWVMInQ3TWJnSrp3vd8e3IQwxwV6H9WJmYcIexe6PqbSsX4BRsEa5XTIkNaCDJNL5wIKZ0CRI1Phx5GUyJwdttHmrA1s9eozCku7atchF_5bejPCH0UYbQJN0GqDWLCQA

# Apply profile temp
aws sts get-caller-identity --profile bys-admin

# Apply profile
export AWS_PROFILE=shared-admin
unset AWS_PROFILE

# list instance profiles 
aws iam list-instance-profiles

vpc

# Endpoint
aws ec2 describe-vpc-endpoints

# Network Interface
aws ec2 describe-network-interfaces

aws ec2 describe-network-interfaces --filters Name=network-interface-id,Values=eni-0a42e5d6bbd8aa4a2

aws ec2 describe-subnets --filters Name=tag:Name,Values=kubernetes.io/role/internal-elb

ec2

# Describe EC2
aws ec2 describe-instances
aws ec2 describe-instances --instance-ids i-0d701ff0b973d86f2
aws ec2 describe-instances --filters Name=instance-id,Values=i-0d701ff0b973d86f2
aws ec2 describe-instances --filters Name=tag:Name,Values=bastion
aws ec2 describe-instances --filters Name=tag:Name,Values=kube-master-node
aws ec2 describe-instances --filters Name=tag:Name,Values=kube-master-node Name=tag:Owner,Values=kyle

# Security Group
aws ec2 describe-security-groups
aws ec2 describe-security-groups --filters Name=group-id,Values=sg-007ce7fc21e3a1544
aws ec2 describe-security-groups --filters "Name=vpc-id,Values=vpc-082c840d344b7c8fb" --query "SecurityGroups[*].{Name:GroupName,ID:GroupId}"

aws ec2 describe-instances --filters Name=tag:Name,Values=bys-dev-ec2-cdp --query "Reservations[*].Instances[*].{InstanceId:InstanceId, State:{Code:State.Code, Name:State.Name}}"

# AutoScaling Group & Launch Template
aws autoscaling describe-auto-scaling-groups
aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names bys-dev-asg-ecs-main-node

# Can see managed VPC account
aws autoscaling describe-notification-configurations --auto-scaling-group-names eks-MNG-b0c5759f-f175-38b4-772f-ed90d371b8e6

aws ec2 describe-launch-templates 
aws ec2 describe-launch-templates --launch-template-ids lt-0a0d96925db65c746

aws ec2 describe-spot-fleet-requests

elb

# Describe LB
aws elbv2 describe-load-balancers | jq '.LoadBalancers'
aws elbv2 describe-load-balancers | jq -r '.LoadBalancers[].LoadBalancerArn'

# TG
aws elbv2 describe-target-groups
aws elbv2 describe-target-health --target-group-arn arn:aws:elasticloadbalancing:ap-northeast-2:558846430793:targetgroup/k8s-ingressn-ingressn-40248d2b72/cd9fae481e7135ce

# Delete LB
aws elbv2 delete-load-balancer --load-balancer-arn arn

# Describe Listener
aws elbv2 describe-listeners --load-balancer-arn arn

# Delete Listener
aws elbv2 delete-listener --listener-arn

# Delete TG
aws elbv2 delete-target-group --target-group-arn arn

eks

aws eks list-addons --cluster-name bys-dev-eks-main
aws eks describe-addon --cluster-name bys-dev-eks-main --addon-name vpc-cni

# Update kube-config
aws eks update-kubeconfig --name bys-dev-eks-main --alias eks-main --region ap-northeast-2
aws eks update-kubeconfig --name bys-dev-eks-v121 --alias eks-v121 --region ap-northeast-2
aws eks update-kubeconfig --name bys-dev-eks-v122 --alias eks-v122 --region ap-northeast-2
aws eks update-kubeconfig --name bys-dev-eks-v123 --alias eks-v123 --region ap-northeast-2
aws eks update-kubeconfig --name bys-dev-eks-v124 --alias eks-v124 --region ap-northeast-2
aws eks update-kubeconfig --name bys-dev-eks-v125 --alias eks-v125 --region ap-northeast-2
aws eks update-kubeconfig --name bys-dev-eks-v126 --alias eks-v126 --region ap-northeast-2
aws eks update-kubeconfig --name bys-dev-eks-v127 --alias eks-v127 --region ap-northeast-2
aws eks update-kubeconfig --name bys-dev-eks-test --alias eks-test --region ap-northeast-2

# Update Node Group version
aws eks update-nodegroup-version --cluster-name bys-dev-eks-main --nodegroup-name ng-v1
aws eks update-nodegroup-version --cluster-name bys-dev-eks-sec --nodegroup-name ng-v1
aws eks update-nodegroup-version --cluster-name bys-dev-eks-win --nodegroup-name ng-v1
aws eks update-nodegroup-version --cluster-name bys-dev-eks-test --nodegroup-name ng-v1
aws eks update-nodegroup-version --cluster-name bys-dev-eks-v124 --nodegroup-name ng-v1
aws eks update-nodegroup-version --cluster-name bys-dev-eks-v125 --nodegroup-name ng-v1
aws eks update-nodegroup-version --cluster-name bys-dev-eks-v126 --nodegroup-name ng-v1
aws eks update-nodegroup-version --cluster-name bys-dev-eks-v127 --nodegroup-name ng-v1

eksctl create iamidentitymapping --cluster bys-dev-eks-v123 --region=ap-northeast-2 --arn arn:aws:iam::558846430793:role/AdminDevAccountRole --group system:masters --username AdminDev
eksctl create iamidentitymapping --cluster bys-dev-eks-test --region=ap-northeast-2 --arn arn:aws:iam::558846430793:role/KarpenterInstanceNodeRole --group system:nodes,system:nodes --username system:node:

patch.sh

#!/bin/bash
EKS_CLUSTERS=$(aws eks list-clusters --query "clusters[*]" --output text)

for EKS_CLUSTER in "${EKS_CLUSTERS[@]}"
do
  echo $EKS_CLUSTER
  echo "1"
  NODE_GROUPS=$(aws eks list-nodegroups --cluster-name $EKS_CLUSTER --query "nodegroups[*]" --output text)

  for NODE_GROUP in "${NODE_GROUPS[@]}"
  do
    echo "2"
    echo $NODE_GROUP

  done
done

ecs

aws ecs list-container-instances --cluster ecs-bys-cluster
aws ecs describe-container-instances --cluster ecs-training-cluster --container-instances container_instance_ID

aws ecs delete-service --force --cluster ecs-traning-cluster --service redis-service 
aws ecs delete-cluster --cluster test

aws ecs list-task-definitions | jq -r '.taskDefinitionArns[]'
aws ecs list-task-definitions --query "taskDefinitionArns[*]" --output text
aws ecs deregister-task-definition --task-definition arn

aws ecs list-task-definitions | 

monitoring_ecs.sh

#!/bin/bash
ECS_CLUSTER_NAME=$1

TOTAL_RUNNING_COUNT=0
TOTAL_DESIRED_COUNT=0
TOTAL_MAXINUM_COUNT=0


echo "ServiceName | DesiredCount | RunningCount | MaximumCount" >> data.txt
for SERVICE_ARN in $(aws ecs list-services --cluster ${ECS_CLUSTER_NAME} | jq -r ".serviceArns[]"); do
    SERVICE_NAME=$(echo ${SERVICE_ARN} | cut -d '/' -f3)

    DESIRED_COUNT=$(aws ecs describe-services --cluster ${ECS_CLUSTER_NAME} --service ${SERVICE_NAME} | jq -r ".services[].desiredCount")
    RUNNING_COUNT=$(aws ecs describe-services --cluster ${ECS_CLUSTER_NAME} --service ${SERVICE_NAME} | jq -r ".services[].runningCount")
    MAXIMUN_COUNT=$(aws  application-autoscaling describe-scalable-targets --service-namespace ecs --resource-ids service/${ECS_CLUSTER_NAME}/${SERVICE_NAME} | jq -r ".ScalableTargets[].MaxCapacity")

    if [ -z $MAXIMUN_COUNT ]
    then
        MAXIMUN_COUNT=0
    fi;

    let TOTAL_DESIRED_COUNT=$TOTAL_DESIRED_COUNT+$DESIRED_COUNT
    let TOTAL_RUNNING_COUNT=$TOTAL_RUNNING_COUNT+$RUNNING_COUNT
    let TOTAL_MAXINUM_COUNT=$TOTAL_MAXINUM_COUNT+$MAXIMUN_COUNT

    echo "$SERVICE_NAME | $DESIRED_COUNT | $RUNNING_COUNT | $MAXIMUN_COUNT" >> data.txt
done

cat data.txt  | column -t -s "|"
rm -rf data.txt

ecr

#ECR Login
aws ecr get-login-password --region ap-northeast-2 | docker login --username AWS --password-stdin 602401143452.dkr.ecr.ap-northeast-2.amazonaws.com

aws ecr get-login-password --region ap-northeast-2 | docker login --username AWS --password-stdin 558846430793.dkr.ecr.ap-northeast-2.amazonaws.com

aws ecr get-login-password --region ap-northeast-2 | docker login --username AWS --password-stdin "$(aws sts get-caller-identity --query Account --output text).dkr.ecr.ap-northeast-2.amazonaws.com"

AWS_REGION=ap-northeast-2
aws ecr create-repository \
--repository-name web \
--image-scanning-configuration scanOnPush=true \
--region ${AWS_REGION}

aws ecr create-repository \
--repository-name dogs \
--image-scanning-configuration scanOnPush=true \
--region ${AWS_REGION}

appmesh

# List VirtualService
aws appmesh list-virtual-services --mesh-name bys-dev-appmesh-eks-main
aws appmesh list-virtual-services --mesh-name bys-dev-appmesh-eks-main | jq -r '.virtualServices[].virtualServiceName'

# Delete VirtualService
aws appmesh delete-virtual-service --mesh-name bys-dev-appmesh-eks-main --virtual-service-name awssdk-storage-dev-svc.aws.svc.cluster.local
aws appmesh delete-virtual-service --mesh-name bys-dev-appmesh-eks-main --virtual-service-name awssdk-iam-dev-svc.aws.svc.cluster.local

# List Routes
aws appmesh list-routes --mesh-name bys-dev-appmesh-eks-main --virtual-router-name awssdk-storage-dev-appmesh-vr_aws | jq -r '.routes[].routeName'
aws appmesh list-routes --mesh-name bys-dev-appmesh-eks-main --virtual-router-name awssdk-ec2-dev-appmesh-vr_aws | jq -r '.routes[].routeName'
aws appmesh list-routes --mesh-name bys-dev-appmesh-eks-main --virtual-router-name awssdk-iam-dev-appmesh-vr_aws | jq -r '.routes[].routeName' 

# Delete Routes
aws appmesh delete-route --mesh-name bys-dev-appmesh-eks-main --virtual-router-name awssdk-storage-dev-appmesh-vr_aws --route-name awssdk-storage-dev-appmesh-r
aws appmesh delete-route --mesh-name bys-dev-appmesh-eks-main --virtual-router-name awssdk-ec2-dev-appmesh-vr_aws --route-name awssdk-ec2-dev-appmesh-r
aws appmesh delete-route --mesh-name bys-dev-appmesh-eks-main --virtual-router-name awssdk-iam-dev-appmesh-vr_aws --route-name awssdk-iam-dev-appmesh-r

# List VirtualRouter
aws appmesh list-virtual-routers --mesh-name bys-dev-appmesh-eks-main
aws appmesh list-virtual-routers --mesh-name bys-dev-appmesh-eks-main | jq -r '.virtualRouters[].virtualRouterName'

# Delete VirtualRouter
aws appmesh delete-virtual-router --mesh-name bys-dev-appmesh-eks-main --virtual-router-name awssdk-storage-dev-appmesh-vr_aws
aws appmesh delete-virtual-router --mesh-name bys-dev-appmesh-eks-main --virtual-router-name awssdk-ec2-dev-appmesh-vr_aws
aws appmesh delete-virtual-router --mesh-name bys-dev-appmesh-eks-main --virtual-router-name awssdk-iam-dev-appmesh-vr_aws

# List VirtualNode
aws appmesh list-virtual-nodes --mesh-name bys-dev-appmesh-eks-main 
aws appmesh list-virtual-nodes --mesh-name bys-dev-appmesh-eks-main  | jq -r '.virtualNodes[].virtualNodeName'

# Delete VirtualNode
aws appmesh delete-virtual-node --mesh-name bys-dev-appmesh-eks-main --virtual-node-name awssdk-ec2-dev-appmesh-vn_aws
aws appmesh delete-virtual-node --mesh-name bys-dev-appmesh-eks-main --virtual-node-name awssdk-storage-dev-appmesh-vn_aws
aws appmesh delete-virtual-node --mesh-name bys-dev-appmesh-eks-main --virtual-node-name awssdk-iam-dev-appmesh-vn_aws

codebuild

# Create Template
aws codebuild create-project --generate-cli-skeleton > codebuild-sample.json

# List Project
aws codebuild list-projects

# View a build project's details
aws codebuild batch-get-projects --names bys-shared-cdb-awssdk-iam-dev

# Create Project
aws codebuild create-project --cli-input-json file://cdb-dashboard.json

# Update Project
aws codebuild update-project --name bys-shared-cdb-awssdk-iam-dev --cli-input-json file://cdb-dashboard.json

codepipeline

# Get Pipeline
aws codepipeline get-pipeline --name bys-shared-cdpl-awssdk-iam-dev
aws codepipeline get-pipeline --name bys-shared-cdpl-awssdk-storage-dev

# Create Pipeline
aws codepipeline create-pipeline --cli-input-json file://cdpl-dev.json

# Update Pipeline
aws codepipeline update-pipeline --cli-input-json file://cdpl-dev.json

aws codepipeline start-pipeline-execution --name name

codedeploy

# Get Deployment Group
aws deploy get-deployment-group --application-name bys-dev-cddp-ecs-main-awssdk-iam --deployment-group-name bys-dev-cddpg-ecs-main-awssdk-iam

# Get Deployment Group ID
aws deploy get-deployment-group --application-name bys-dev-cddp-ecs-main-awssdk-iam --deployment-group-name bys-dev-cddpg-ecs-main-awssdk-iam | jq -r ".deploymentGroupInfo.deploymentGroupId"

# Get Deployment 
aws deploy get-deployment --deployment-id d-TV9TFBZS9

efs

mkdir -p /efs/bys-dev-efs-eks-v122
sudo mount -t nfs -o nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport fs-057778ed087bb0e63.efs.ap-northeast-2.amazonaws.com:/   /efs/bys-dev-efs-eks-v122

s3

# S3 Copy with kms key encryption
aws s3 cp codeseries/appspec.yml s3://bys-shared-s3-codeseries-awssdk-iam/dev/artifacts/appspec.yml --sse aws:kms --sse-kms-key-id 42490b53-71d6-4265-9dab-8d4eddc90d97

cloudfront

aws cloudfront create-invalidation --distribution-id E1H6SYS9DTGCA --paths "/index.html"

cloudformation

# Stack Create
aws cloudformation create-stack --stack-name eks-lab-test1 --template-body file://01_main_vpc_settings.yml --parameters ParameterKey=KeyName,ParameterValue=bys-console
aws cloudformation create-stack --stack-name profile-cfn-test --template-url https://s3.amazonaws.com/cloudformation-examples/user-guide/cross-stack/SampleNetworkCrossStack.template

aws cloudformation list-stacks
aws cloudformation describe-stacks --stack-name profile-cfn-test
aws cloudformation create-change-set \
--stack-name profile-cfn-test --change-set-name test --template-body file://profile-cfn-test.json \
--parameters ParameterKey=homeIp,ParameterValue=$(curl -s http://checkip.amazonaws.com/)/32




aws cloudformation update-stack \
--stack-name profile-cfn-test --template-body file://profile-cfn-test.json \
--parameters ParameterKey=homeIp,ParameterValue=$(curl -s http://checkip.amazonaws.com/)/32
 { 
  "AWSTemplateFormatVersion" : "2010-09-09",
  "Description" : "AWS CloudFormation Sample Template VPC_with_PublicIPs_And_DNS: Sample template that creates a VPC with DNS and public IPs enabled. Note that you are billed for the AWS resources that you use when you create a stack from this template.",

  "Parameters": {
    "homeIp": {
        "Type": "String",
        "Description": "my changing ip"
    }
  },
  "Resources" : {
    "VPC" : {
      "Type" : "AWS::EC2::VPC",
      "Properties" : {
        "EnableDnsSupport" : "true",
        "EnableDnsHostnames" : "true",
        "CidrBlock" : "10.0.0.0/16"
      }
    },
    "PublicSubnet" : {
      "Type" : "AWS::EC2::Subnet",
      "Properties" : {
        "VpcId" : { "Ref" : "VPC" },
        "CidrBlock" : "10.0.0.0/24"
      }
    },
    "InternetGateway" : {
      "Type" : "AWS::EC2::InternetGateway"
    },
    "VPCGatewayAttachment" : {
       "Type" : "AWS::EC2::VPCGatewayAttachment",
       "Properties" : {
         "VpcId" : { "Ref" : "VPC" },
         "InternetGatewayId" : { "Ref" : "InternetGateway" }
       }
    },
    "PublicRouteTable" : {
      "Type" : "AWS::EC2::RouteTable",
      "Properties" : {
        "VpcId" : { "Ref" : "VPC" }
      }
    },
    "PublicRoute" : {
      "Type" : "AWS::EC2::Route",
      "DependsOn" : "VPCGatewayAttachment",
      "Properties" : {
        "RouteTableId" : { "Ref" : "PublicRouteTable" },
        "DestinationCidrBlock" : "0.0.0.0/0",
        "GatewayId" : { "Ref" : "InternetGateway" }
      }
    },
    "PublicSubnetRouteTableAssociation" : {
      "Type" : "AWS::EC2::SubnetRouteTableAssociation",
      "Properties" : {
        "SubnetId" : { "Ref" : "PublicSubnet" },
        "RouteTableId" : { "Ref" : "PublicRouteTable" }
      }
    },
    "PublicSubnetNetworkAclAssociation" : {
      "Type" : "AWS::EC2::SubnetNetworkAclAssociation",
      "Properties" : {
        "SubnetId" : { "Ref" : "PublicSubnet" },
        "NetworkAclId" : { "Fn::GetAtt" : ["VPC", "DefaultNetworkAcl"] }
      }
    },
    "WebServerSecurityGroup" : {
      "Type" : "AWS::EC2::SecurityGroup",
      "Properties" : {
        "GroupDescription" : "Enable HTTP ingress",
        "VpcId" : { "Ref" : "VPC" },
        "SecurityGroupIngress" : [ { 
          "IpProtocol" : "tcp",
          "FromPort" : "80",  
          "ToPort" : "80",
          "CidrIp" : "0.0.0.0/0"
        },
        { 
          "IpProtocol" : "tcp",
          "FromPort" : "22",  
          "ToPort" : "22",
          "CidrIp" : { "Ref" : "homeIp" }
        } ]
      }
    }
  },
  "Outputs" : {
    "VPCId" : {
      "Description" : "VPC ID",
      "Value" :  { "Ref" : "VPC" },
      "Export" : { "Name" : {"Fn::Sub": "${AWS::StackName}-VPCID" }}
    },
    "PublicSubnet" : {
      "Description" : "The subnet ID to use for public web servers",
      "Value" :  { "Ref" : "PublicSubnet" },
      "Export" : { "Name" : {"Fn::Sub": "${AWS::StackName}-SubnetID" }}
    },
    "WebServerSecurityGroup" : {
      "Description" : "The security group ID to use for public web servers",
      "Value" :  { "Fn::GetAtt" : ["WebServerSecurityGroup", "GroupId"] },
      "Export" : { "Name" : {"Fn::Sub": "${AWS::StackName}-SecurityGroupID" }}
    }
  }
}

Tag: [ aws  cli  ]