3

I am running a user-data script on startup of an ec2 machine which shuts the machine down after checking the exit status of the last executed command. I confirmed that the last executed command ran successfully, so I am not sure why the machine is not terminating. This doesn't happen every time, it seems to only happen when the user-data script finishes quickly.

Here is the end of my bash script (after executing several commands):

python myscript.py
ret=$?
echo $ret
if [[ $ret -eq 0 ]]; then
    shutdown now
fi

This produces the following output, but does not terminate the instance:

0
Cloud-init v. 0.7.9 running 'init-local' at Wed, 28 Nov 2018 20:15:38 +0000. Up 11.12 seconds.
Cloud-init v. 0.7.9 running 'init' at Wed, 28 Nov 2018 20:15:41 +0000. Up 14.67 seconds.
ci-info: ++++++++++++++++++++++++++Net device info+++++++++++++++++++++++++++
ci-info:  Device   Up     Address         Mask      Scope      Hw-Address
ci-info:   lo:    True   127.0.0.1     255.0.0.0      .            .
ci-info:   lo:    True       .             .          d            .
ci-info:  eth0:   True  10.90.1.222  255.255.255.0    .    0e:c9:6e:60:5d:e8
ci-info:  eth0:   True       .             .          d    0e:c9:6e:60:5d:e8
ci-info: +++++++++++++++++++++++++++Route IPv4 info++++++++++++++++++++++++++++
ci-info:  Route    Destination     Gateway       Genmask      Interface  Flags
ci-info:    0        0.0.0.0      10.90.1.1      0.0.0.0         eth0      UG
ci-info:    1       10.90.1.0      0.0.0.0    255.255.255.0      eth0      U
ci-info:    2    169.254.169.254   0.0.0.0   255.255.255.255     eth0      UH
Cloud-init v. 0.7.9 running 'modules:config' at Wed, 28 Nov 2018 20:15:44 +0000. Up 17.35 seconds.
Cloud-init v. 0.7.9 running 'modules:final' at Wed, 28 Nov 2018 20:15:45 +0000. Up 18.45 seconds.
Connection to 10.90.1.222 closed by remote host. 20:15:46 +0000. Datasource DataSourceEc2.  Up 19.56 seconds

I am trying to determine if Cloud-init is somehow preventing the instance from terminating. Is it because the script finished while other background processes were still initializing?

1 Answers1

4

I recently had this problem, and the solution that worked for me was changing the shutdown command to explicitly request poweroff instead of halt:

shutdown -P now

The AWS docs at https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html say:

By default, when you initiate a shutdown from an Amazon EBS-backed instance (using a command such as shutdown or poweroff), the instance stops (Note that halt does not issue a poweroff command and, if used, the instance will not terminate; instead, it will place the CPU into HLT and the instance will remain running).