Search code examples
amazon-web-servicesshellaws-clisystemdsystemctl

Start service script using AWS CLI?


I am trying to configure an EC2 instance with auto-communication with a specific AWS SQS at the time the instance boots up. For this, I wrote a systemd startup script which will execute the shell-script.

[Unit]
Description=NewUnit

[Service]
ExecStart=/usr/local/bin/startup_script.sh

[Install]
WantedBy=default.target

The shell script basically measures the CPU usage of the instance and sends this information to the queue. The critical part, which makes my plan fail is the line where I try to invoke the aws cli function 'send-message':

while true; do
CONTENT='{"vmid":{"DataType":"String","StringValue":"'$(getEC2ID)'"},"vmcpu":{"DataType":"Number","StringValue":"'$(getCPU)'"},"vmmemory":{"DataType":"Number","StringValue":"'$(getMemory)'"},"vmdisk":{"DataType":"Number","StringValue":"12345"}}'

aws sqs send-message \
    --queue-url "$QUEUE_URL" \
    --message-body "$CONTENT" \
    --message-group-id "$GROUP_ID" \
    --message-deduplication-id "$(getID)" \
#    --message-attributes "$CONTENT" \ || echo "not yet" >>/usr/local/bin/startup_report.txt
done

I guess the problem is that the awscli is not yet ready when the script is executed. So my question at this point is: how can I use systemd to wait for the awscli to execute this shell script afterwards?


Solution

  • The way you wrote your service file doesn't specify any ordering or requirements. That allows systemd to run it anytime it wishes to. In particular this might be long time before network is up, as it was in case of my script using aws cli. Adding following directive to Unit section of your file:

    After=network.target
    

    ...will make it run after network is up. If this will not work for you, then you might wanna change it to:

    After=network-online.target
    

    ...which should guarantee full network operation when your script runs.