Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloudformation template completes deployment before UserData is finished

Tags:

In the CloudFormation template I am deploying, I am running a long running operation in the UserData block.

It looks as follows:

"UserData": {
    "Fn::Base64" : {
        "Fn::Join" : [
            "",
            [
            "/usr/local/bin/mylongrunningscript.sh"
            ]
         ]
    }
}

The contents of the script are:

echo "UserData starting!" > /var/log/mycustomlog.log
sleep 300
echo "UserData finished!" >> /var/log/mycustomlog.log

The issue I am seeing is that I believe the CloudFormation template is completing it's deployment before the UserData script finishes running. I believe this is the case because if I am quick enough and ssh into the instance, I will see something as follows:

$ cat /var/log/mycustomlog.log
UserData starting

which suggests that the UserData didn't finish running


How can I make sure that the UserData code execution is completed before the stack is in the "CreateComplete" status?

like image 332
Paolo Avatar asked Feb 24 '20 17:02

Paolo


1 Answers

To ensure the CloudFormation template waits for the completion of the UserData script, you must do two things:

  1. Add a CreationPolicy to the resource you are targeting (virtual machine in my case).

  2. Add logic in the script to signal its completion. This custom logic uses the cfn-signal utility, which you might have to install in your instance.


Here's how the template looks now:

"UserData": {
    "Fn::Base64" : {
        "Fn::Join" : [
            "",
            [
            "/usr/local/bin/mylongrunningscript.sh"
            ]
        ]
    }
},
"CreationPolicy": {
    "ResourceSignal" : {
        "Count": "1",
        "Timeout": "PT10M"
    }
}

The cfn-signal utility is used to signal the termination of the script:

"/home/ubuntu/aws-cfn-bootstrap-*/bin/cfn-signal -e $? ",
" --stack ", { "Ref": "AWS::StackName" },
" --resource MyInstance" ,
" --region ", { "Ref" : "AWS::Region" }, "\n"

See here for a Windows example.

like image 149
Paolo Avatar answered Sep 30 '22 16:09

Paolo