Search code examples
amazon-ec2aws-code-deploy

EC2 `UserData` execution callback?


I have a Cloudformation template which creates a VPC/Subnet and launches a single EC2 machine within it -

https://gist.github.com/jhw/9c595edb615381780a2ba76791722fc3#file-stack-yaml

The template also contains some EC2 UserData which installs Cloudwatch and CodeDeploy user agents on that machine.

The template works fine but I'm struggling how to get notified as to when the UserData has actually been executed - it seems that the EC2 machine will say "ready" but only then starts to execute UserData, which subsequently takes a couple of minutes due to the need to load/install different packages.

The only way I have been able to get visibility on how UserData execution is going is to dump the EC2 machine level logs, but this is far from perfect as the logs don't seem to be available until the UserData has completed execution - if you try to download them prior to successful execution then you just get an empty file.

So my "automated" routine for detecting whether the machine is really ready is to fetch the logs on a timed loop, and then try and detect certain keywords in those logs.

This feels, ahem, suboptimal :-/

Is there a better way of getting notified when UserData may have completed execution ? Some kind of callback ?


Solution

  • CreationPolicy Documentation Associate the CreationPolicy attribute with a resource to prevent its status from reaching create complete until AWS CloudFormation receives a specified number of success signals or the timeout period is exceeded.

    In Instance CloudFormation use CreationPolicy with Count=1:

    CreationPolicy:
      ResourceSignal:
        Count: '1'
        Timeout: PT15M
    

    and then send this signal as a last line of the UserData script:

    cfn-signal -e $? --stack ${AWS::StackName} --resource MyEC2Instance --region ${AWS::Region}