I have a classic load balancer on AWS with a key tag "Owner" and value "engineer". Is there any way to retrieve the name of this load balancer by this tag using aws cli?
AWS cli does not have native ways to do it.
You can use jq with AWS cli
for i in $(aws elbv2 describe-load-balancers | jq -r '.LoadBalancers[].LoadBalancerArn'); do aws elbv2 describe-tags --resource-arns "$i" | jq -ce '.TagDescriptions[].Tags[] | select( .Key == "Owner" and .Value == "engineer")' && echo "$i" ;done
Related
I want to delete all load balancers returned form my query below. The problem is creating an array, then looping through each item to delete from my Groovy pipeline script in Jenkins.
def load_balancer_names = sh(returnStdout: true, script: """ aws elbv2 describe-load-balancers | jq '[.LoadBalancers[] | select(.LoadBalancerName | startswith("loadbalancer-alb-")) | { LoadBalancerARN: .LoadBalancerARN } ]' """)
echo "Load balancer list: ${load_balancer_names}"
JSON output:
Load balancer list: [
{
"LoadBalancerName": "arn:aws:elasticloadbalancing:us-east-1:...-123"
},
{
"LoadBalancerName": "arn:aws:elasticloadbalancing:us-east-1:...-657"
}
]
AWS CLI delete command to delete load balancers:
aws elbv2 delete-load-balancer \
--load-balancer-arn [load balancer ARN]
This should work for you:
aws elbv2 describe-load-balancers --query "LoadBalancers[?starts_with(LoadBalancerName,'loadbalancer-alb-')].LoadBalancerArn" --output text | tr "\t" "\n" | xargs -I{} aws elbv2 delete-load-balancer --load-balancer-arn {}
this command, which doesn't require jq and only uses the AWS CLI, extracts the load balancer ARNs and then feeds them to xargs for deletion
I'm trying to write a script that will delete all available volumes that are up for more than 1 hour.
So I took the line that filters the volumes by state
aws ec2 describe-volumes --filters Name=status,Values=available | jq '.Volumes[]'
And I tried to combine it with another query I have for filtering snapshots by time creation
aws ec2 describe-snapshots --owner self --output json | jq '.Snapshots[] | select(.StartTime < "'$(date --date='-1 month' '+%Y-%m-%d')'") | [.Description, .StartTime, .SnapshotId]'
So I combined this query but it does not return any volume
aws ec2 describe-volumes --filters Name=status,Values=available | jq '.Volumes[] | select(.CreateTime < "'$(date --date='-1 hour' '+%Y-%m-%d')'") | [.VolumeId]'
And another weird thing, if I replace CreateTime with blabla the query does not fail but returns me the volume
~ $ aws ec2 describe-volumes --filters Name=status,Values=available | jq '.Volumes[] | select(.blabla < "'$(date --date='-1 hour' '+%Y-%m-%d')'") | [.VolumeId]'
Found another way to do this
aws ec2 describe-volumes --filters Name=status,Values=available --query "Volumes[?(CreateTime<'$(date --date='-1 day' '+%Y-%m-%d')')].[VolumeId]" --output text
Wrote a script to add instances to the AWS target group
#!/bin/bash
export AWS_PROFILE=***
export AWS_DEFAULT_REGION=eu-central-1
for INST_NAME in $(aws ec2 describe-instances --query 'Reservations[].Instances[].Tags[?Key==`Name`].Value' --output text | sort); do
echo "check ${INST_NAME} in Target Group"
TARGET_GROUP=$(aws elbv2 describe-target-groups|jq -r '.[]|.[].TargetGroupArn'| grep ${INST_NAME})
RUNNING_INSTANCES=$(aws ec2 describe-instances| jq '.Reservations[].Instances[] | select(.Tags[].Value=="${INST_NAME}")'| jq -r .InstanceId| sort | uniq | wc -l)
COUNT=$(aws elbv2 describe-target-health --target-group-arn ${TARGET_GROUP}|jq -r '.TargetHealthDescriptions[].Target.Id'| wc -l)
if [[ ${RUNNING_INSTANCES} = ${COUNT} ]]; then
echo "VSE OK"
else
echo "dobavit ${RUNNING_INSTANCES} v ${TARGET_GROUP}"
for INSTANCE_ID in $(aws ec2 describe-instances --filter Name=tag-key,Values=Name --query "Reservations[*].Instances[*].{Instance:InstanceId,Name:Tags[?Key=='Name']|[0].Value}"|jq ".[][]|select(.Name==\"${TAGS}\")"|jq -r .Instance); do
ASG=$(aws autoscaling describe-auto-scaling-instances|jq '.AutoScalingInstances'|jq ".[]|select(.InstanceId==\"${INSTANCE_ID}\")"|jq -r .InstanceId)
echo "Updating ${TARGET_GROUP} to add instances from ${ASG}"
aws elbv2 register-targets --target-group-arn ${TARGET_GROUP} --targets "Id="${ASG}
done
fi
done
but he doesn't add. Need select all instances by tag and compare with the number in the target group, if the number is different, then add all instances with the tag to the target group
Update, it's working
for INSTANCE_NAME in $(aws ec2 describe-instances --query 'Reservations[].Instances[].Tags[?Key==`Name`].Value' --output text | sort | uniq ); do
echo "check ${INSTANCE_NAME} in Target Group"
TARGET_GROUP=$(aws elbv2 describe-target-groups|jq -r '.[]|.[].TargetGroupArn'| grep ${INSTANCE_NAME})
if ! [ -z "${TARGET_GROUP}" ]; then
for i in $(echo ${TARGET_GROUP}); do
RUNNING_INSTANCES=$(aws ec2 describe-instances| jq ".Reservations[].Instances[] | select(.Tags[].Value==\"${INSTANCE_NAME}\")"| jq -r .InstanceId| sort | uniq | wc -l)
COUNT=$(aws elbv2 describe-target-health --target-group-arn ${i}|jq -r '.TargetHealthDescriptions[].Target.Id'| wc -l)
if ! [[ ${RUNNING_INSTANCES} = ${COUNT} ]]; then
for INSTANCE_ID in $(aws ec2 describe-instances --filter Name=tag-key,Values=Name --query "Reservations[*].Instances[*].{Instance:InstanceId,Name:Tags[?Key=='Name']|[0].Value}"|jq ".[][]|select(.Name==\"${INSTANCE_NAME}\")"|jq -r .Instance); do
ASG=$(aws autoscaling describe-auto-scaling-instances|jq '.AutoScalingInstances'|jq ".[]|select(.InstanceId==\"${INSTANCE_ID}\")"|jq -r .InstanceId)
aws elbv2 register-targets --target-group-arn ${i} --targets "Id="${ASG}
echo "Updating ${TARGET_GROUP} to add instances from ${ASG}"
done
fi
done
fi
done
I have multiple aws accounts and i don't remember in which aws account this EC2 instance was created, is there any optimal way to figure out in very less time?
Note: i need to know account DNS name or Alias name.(Not account number)
If you have access to the instance you could use Instance metadata API:
[ec2-user ~]$ curl http://169.254.169.254/latest/dynamic/instance-identity/document
It returns json with accountId field.
If you configure AWS CLI for all account, then you can get the Account ID, ARN and user ID.
The script does the following.
Get the list of AWS configuration profile
Loop over all profile
Get a list of All Ec2 public IP address
print account info if IP matched and exit
RUN
./script.sh 52.x.x.x
script.sh
#!/bin/bash
INSTANCE_IP="${1}"
if [ -z "${INSTANCE_IP}" ]; then
echo "pls provide instance IP"
echo "./scipt.sh 54.x.x.x"
exit 1
fi
PROFILE_LIST=$(grep -o "\\[[^]]*]" < ~/.aws/credentials | tr -d "[]")
for PROFILE in $PROFILE_LIST; do
ALL_IPS=$(aws ec2 describe-instances --profile "${PROFILE}" --query "Reservations[].Instances[][PublicIpAddress]" --output text | tr '\r\n' ' ')
echo "looking against profile ${PROFILE}"
for IP in $ALL_IPS; do
if [ "${INSTANCE_IP}" == "${IP}" ]; then
echo "Instance IP matched in below account"
aws sts get-caller-identity
exit 0
fi
done
done
echo "seems like instance not belong to these profile"
echo "${PROFILE_LIST}"
exit 1
loop over accounts
loop over regions
also be aware of lightsail!
I came up with the following and helped me. I didn't exclude the regions that did not have lightsail
for region in `aws ec2 describe-regions --output text --query 'Regions[*].[RegionName]' --region eu-west-1` ; do \
echo $region; \
aws ec2 describe-network-interfaces --output text --filters Name=addresses.private-ip-address,Values="IPv4 address" --region $region ; \
aws lightsail get-instances --region eu-west-1 --output text --query 'instances[*].[name,publicIpAddress]' --region $region; \
done
I am trying to delete the security groups by running the command
for i in `aws ec2 describe-security-groups --filters Name=vpc-id,Values="${vpcid}" | grep sg- | sed -E 's/^.*(igw-[a-z0-9]+).*$/\1/'`; do aws ec2 delete-security-group --group-id $i; done
It will delete the custom security group successfully. However, return an error when trying to delete a default security group. I don't want the error to be returned on the terminal, and instead just return nothing.
I have tried to add || true at the end of delete-security-group command, which looks like
for i in `aws ec2 describe-security-groups --filters Name=vpc-id,Values="${vpcid}" | grep sg- | sed -E 's/^.*(igw-[a-z0-9]+).*$/\1/'`; do aws ec2 delete-security-group --group-id $i || true; done
while the error is still printed on the terminal. Any helps
using command 2>/dev/null to redirect the error