Ubuntu – Start service after AWS user-data has run

amazon-web-servicessystemdUbuntuubuntu-16.04

I am building an AMI based off of an Ubuntu 16.04 AMI.

When I start an instance from my AMI, I would like to pass in a user-data script that runs before the service start up on the AMI.

It looks like the user-data is run in cloud-final.service. If I systemctl status cloud-final or journalctl -u cloud-final I see the output of my user-data script.

I tried to set up my .service file to start the service after cloud-final.service

[Unit]
Description=My Service
After=network.service
After=cloud-final.service

...

but cloud-final has RemainAfterExit=yes, which means it never completes, so my service never starts.

How can I configure AWS Ubuntu to start my service after the user-data script has been run?

Best Answer

Use

[Unit]
…
After=cloud-final.service
…
[Install]
WantedBy=cloud-init.target

I ran into this as well. journalctl showed user data stuff running after multi-user and before the target cloud-init was reached.

<timestamp> <ip_addr> systemd[1]: Reached target Multi-User System.
[snip]
<timestamp> <ip_addr> systemd[1]: Starting Execute cloud user/final scripts...
<timestamp> <ip_addr> user-data[1592]: my user data stuff
[snip]
<timestamp> <ip_addr> systemd[1]: Started Execute cloud user/final scripts.
[snip]
<timestamp> <ip_addr> systemd[1]: Reached target Cloud-init target.

So I thought to have it be required/wanted by cloud-init instead of the usual multi-user target (which may be what op had), and it just worked.