3

I am building an AMI image on AWS using packer and Ansible. My end goal is to have an AMI image such that when it is built into an EC2 instance, it has my web app running. For me to reach my end goal, I need to configure Nginx server in my AMI. My challenge is I don't have any idea how to get the IP address of the EC2 instance and use it to configure Nginx server. Here is my current configuration of Nginx file:

server {
    listen 80;
    server_name {{ ansible_default_ipv4.address }};

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/home/ubuntu/Yummy-Recipes/Yummy-Recipes-Ch3/yummy-recipes.sock;
    }
}

server_name should hold the value of the EC2 instance it is running on. If you would like to know more about my code than please feel free to visit my repository on GitHub.

Any help will be highly appreciated.

Harith
  • 539
  • 5
  • 16

2 Answers2

2

Since you are creating an AMI you can't use ansible at (image) build time to configure this. Later when you launch a new instance from the created image the IP and hostname will be different.

Instead you should add a cloud-init script that will update the config file everytime a new instance will be launched from the image. You do this by adding a script in /var/lib/cloud/scripts/per-instance/ see cloud-init documentation

Rickard von Essen
  • 4,110
  • 2
  • 23
  • 27
0

You can also use an elastic ip. Assuming that you're going to use your image to spin up just one instance, AWS has an option of an elastic ip which is basically a static ipv4 address. Setup one for your account in your preferred region and then associate it with your instance or network interface at the time of provisioning. Your nginx configuration file should look like this

server {
listen 80;
server_name <your_elastic_ip>;
...
}
Ibrahim M
  • 11
  • 1
  • 2
  • 4