Skip to content

Instantly share code, notes, and snippets.

@muhannad0
Last active August 24, 2024 12:14
Show Gist options
  • Select an option

  • Save muhannad0/45725e53805a4cba0da51a49aefd6c00 to your computer and use it in GitHub Desktop.

Select an option

Save muhannad0/45725e53805a4cba0da51a49aefd6c00 to your computer and use it in GitHub Desktop.
quick-aws-cli-scripts

AWS CLI scripts for quick tasks

Get all the EC2 instances with a specific Name tag, and add/update tags on those resources

aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId, Tags[?Key==`Name` && starts_with(Value, `dev`)]]' --output json | jq -r '.[][] | select(.[1] | length > 0) | .[0]' | \
while read instance_id; do
  aws ec2 create-tags --resources "$instance_id" --tags Key=Environment,Value=development
done
  • jq used to filter out resources that have empty tags and only output the instance ID.

Invoke a Lambda function synchronously with a payload

aws lambda invoke \
  --function-name function1 \
  --cli-binary-format raw-in-base64-out \
  --payload '{"action": "create", "instanceId": "i-abc123" }' \
  out --log-type Tail
  • Better to wrap the payload in double quotes, so that we can substitute bash variables easily. However, it is extra work to escape the key value pairs' quotes.
--payload "{\"action\": \"create\", \"instanceId\": \"$instance_id\" }"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment