AWS user_data at every boot on ec2

Here is a sample of my code:
user_data = "${data.template_file.vault_init_config.rendered}"
Now user_data in aws is loaded only when ec2 machine is creating but I want use another available option in AWS and run it every reboot.
In AWS console I can set it manually by " <persist>true</persist> under the code
How can I do it in terraform? I cannot find it in documentation.

Hi @debek,

An important thing to understand about user_data is that from the perspective of the EC2 API – and therefore from the perspective of Terraform – it’s just an arbitrary bunch of bytes that can be retrieved by software running in the EC2 instance once it boots. For that reason, the interpretation of that data is entirely up to that software.

That’s relevant to your question because the decision to only pay attention to scripts in the user_data is being made by the software in your instance that is reading it, not by Terraform itself or by EC2. That’s why there’s no mention of this in Terraform’s documentation.

If you’re using a typical official Linux distribution image then it’s likely the piece of software handling user_data for you is cloud-init – though probably best to check the docs for your distribution to be sure.

By default, cloud-init only runs the scripts you supply on first boot because it assumes that these scripts will make changes to the filesystem that will cause their effects to be persistent on future boots. That then leads to one strategy for configuring actions that will take effect on future boots: use your initialization script to install something that runs on every boot, so that the script isn’t itself needed on future boots.

I can’t find reference to it in cloud-init's own documentation, but a Stack Overflow question asked about how to force cloud-init to re-run the user scripts on every boot, and there is an answer there of including a special marker in the cloud-config section of the user_data to tell cloud-init to do so:

 - [scripts-user, always]

However, I’m no cloud-init expert by any means; you might be able to get a more detailed answer if you ask in a cloud-init-specific forum. Whatever you learn about the input format of cloud-init, you can assume that from Terraform’s perspective whatever raw data you pass to the user_data argument will be passed to cloud-init to process, and so the Terraform part of solving the problem will be ensuring that the user_data value you set is something cloud-init can interpret.

I’d recommend that you create a scriptfile instead with the contents of the current user_data and upload that - using the multi-section variant of cloud-init - and the the user_data will first call your scriptfile but also put it in /etc/rc.local so it’s run on future boots.