Skip to content

Run cronjob on a single instance #1

@alexander-schranz

Description

@alexander-schranz

I got the following example from @t-richard to run cronjobs only on single instance:

# Source: https://github.com/awsdocs/elastic-beanstalk-samples/blob/master/configuration-files/aws-provided/instance-configuration/cron-leaderonly-linux.config
packages:
  yum:
    jq: []
files:
  "/usr/local/bin/test_cron.sh":
    mode: "000755"
    owner: root
    group: root
    content: |
      #!/bin/bash
      INSTANCE_ID=`curl http://169.254.169.254/latest/meta-data/instance-id 2>/dev/null`
      REGION=`curl -s http://169.254.169.254/latest/dynamic/instance-identity/document 2>/dev/null | jq -r .region`
      # Find the Auto Scaling Group name from the Elastic Beanstalk environment
      ASG=`aws ec2 describe-tags --filters "Name=resource-id,Values=$INSTANCE_ID" \
          --region $REGION --output json | jq -r '.[][] | select(.Key=="aws:autoscaling:groupName") | .Value'`
      # Find the first instance in the Auto Scaling Group
      FIRST=`aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names $ASG \
          --region $REGION --output json | \
          jq -r '.AutoScalingGroups[].Instances[] | select(.LifecycleState=="InService") | .InstanceId' | sort | head -1`
      # If the instance ids are the same exit 0
      [ "$FIRST" = "$INSTANCE_ID" ]
  "/etc/cron.d/cronjobs":
    mode: "000644"
    owner: root
    group: root
    content: |
      * * * * * root /usr/local/bin/test_cron.sh && whatever command you need
commands:
  remove_old_cron:
    command: "rm -fr /etc/cron.d/cron_example.bak"
    ignoreErrors: true

Maybe similar adjustments would be needed to run the supervisor only on one instance.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions