Skip to content

Instantly share code, notes, and snippets.

@tom-butler
Created December 17, 2017 23:15
Show Gist options
  • Save tom-butler/e968a6a7f7f4bb194d33622f923bebdc to your computer and use it in GitHub Desktop.
Save tom-butler/e968a6a7f7f4bb194d33622f923bebdc to your computer and use it in GitHub Desktop.
SSH Run command to run a shell script on a fleet of instances.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ssm:DescribeAssociation",
"ssm:GetDeployablePatchSnapshotForInstance",
"ssm:GetDocument",
"ssm:GetParameters",
"ssm:ListAssociations",
"ssm:ListInstanceAssociations",
"ssm:PutInventory",
"ssm:UpdateAssociationStatus",
"ssm:UpdateInstanceAssociationStatus",
"ssm:UpdateInstanceInformation"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"ec2messages:AcknowledgeMessage",
"ec2messages:DeleteMessage",
"ec2messages:FailMessage",
"ec2messages:GetEndpoint",
"ec2messages:GetMessages",
"ec2messages:SendReply"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"ec2:DescribeInstanceStatus"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"ds:CreateComputer",
"ds:DescribeDirectories"
],
"Resource": "*"
}
]
}
# SSM agent
sudo apt-get update && sudo apt-get install -y build-essential
curl https://amazon-ssm-ap-southeast-2.s3.amazonaws.com/latest/debian_amd64/amazon-ssm-agent.deb -o /tmp/amazon-ssm-agent.deb
sudo dpkg -i /tmp/amazon-ssm-agent.deb
sudo systemctl start amazon-ssm-agent
# Trigger backup
commandId=$(aws ssm send-command --document-name backup_script --targets Key=tag:application,Values=eventstore | jq -r '.Command.CommandId')
instanceIds=$(aws ec2 describe-instances --filters Name=tag:application,Values=eventstore | jq -r '..|.InstanceId? | select(. != null)')
# Check if it worked
attempts=0
until [ $attempts == "10" ]; do
for instance in $instanceIds; do
status=$(aws ssm get-command-invocation --command-id $commandId --instance-id $instance | jq -r '.Status')
if [ $status == "Success" ]; then
echo "Backed up successfully"
exit 0
fi
done
echo "Still waiting, attempt $attempts of 10"
attempts=$(($attempts + 1))
sleep 10
done
echo "Error: Backup Failed"
exit 1
#--------------------------------------------------------------
# Backup Script
#--------------------------------------------------------------
# Generates an SSM document that we can run as an SSM command on our instances.
resource "aws_ssm_document" "backup" {
name = "backup_script"
document_type = "Command"
content = <<DOC
{
"schemaVersion": "1.2",
"description": "Run a backup script",
"parameters": {
},
"runtimeConfig": {
"aws:runShellScript": {
"properties": [
{
"id": "0.aws:runShellScript",
"runCommand": ["/usr/local/bin/backup.sh"]
}
]
}
}
}
DOC
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment