I use Hashicorp Packer to create an AWS ubuntu image. And I need to perform some initialization of instance on first run. I know I can create a script that will run once. But I would like to know is there any out of the box solution since I can find nothing about this in documentation.
Packer is only concerned with building the base AMIs and doesn't really care what happens after that. The best bet would be cloud-init scripts, as this is what they're for. As mentioned on their site:
Cloud-init is the industry standard multi-distribution method for cross-platform cloud instance initialization. It is supported across all major public cloud providers, provisioning systems for private cloud infrastructure, and bare-metal installations.
Amazon's documentation on setting up user-data scripts can be found here: Run commands on your Linux instance at launch.
They include an example of using cloud-init directives:
#cloud-config
repo_update: true
repo_upgrade: all
packages:
- httpd
- mariadb-server
runcmd:
- [ sh, -c, "amazon-linux-extras install -y lamp-mariadb10.2-php7.2 php7.2" ]
- systemctl start httpd
- sudo systemctl enable httpd
- [ sh, -c, "usermod -a -G apache ec2-user" ]
- [ sh, -c, "chown -R ec2-user:apache /var/www" ]
- chmod 2775 /var/www
- [ find, /var/www, -type, d, -exec, chmod, 2775, {}, \; ]
- [ find, /var/www, -type, f, -exec, chmod, 0664, {}, \; ]
- [ sh, -c, 'echo "<?php phpinfo(); ?>" > /var/www/html/phpinfo.php' ]
Beyond this, the other solution if you are spinning up many machines you want to provision in various ways, would be to use a Configuration-as-Code tool such as Puppet, Chef, Ansible or Salt.