Search code examples
amazon-web-servicesamazon-ec2coreoscloud-init

How to use "Instance ID" in cloud-config.yml on CoreOS on EC2?


I have CoreOS instances on Amazon EC2.

There are some pre-defined variables accessible from cloud-config.yml such as "$private_ipv4" or "$public_ipv4".

Is there a way to access "Instance ID" of EC2 instances like "$instance_id"? (I have tried "$instance_id" and "$INSTANCE_ID" but neither of them took effect)


Solution

  • That variable isn't built in, but you could do one of two things:

    1. curl the metadata service for that value directly:

    curl http://169.254.169.254/latest/meta-data/instance-id

    1. have a "oneshot" unit write out a the result of that curl to a file and then source that file in your units, just like you can for environment info.

    The oneshot unit one would write INSTANCE_ID=abc123 to /etc/instance-id and your regular unit would depend on the oneshot (Requires=instanceid.service/After=instanceid.service) contains EnvironmentFile=/etc/instance-id, which would make $INSTANCE_ID available for use in a unit.

    More docs on using env vars in units: https://coreos.com/os/docs/latest/using-environment-variables-in-systemd-units.html#environmentfile-directive