Is it possible to use variables in cloud-config
Asked Answered
S

3

7

When using cloud init's #cloud-config to create configuration files, how would I go about using variables to populate values?

In my specific case I'd like to autostart EC2 instances as preconfigured salt minions. Example of salt minion cloud config

Say I'd like to get the specific EC2 instances id and set that as the salt minion's id.

How would I go about it setting the value dynamically for each instance?

Strep answered 14/5, 2013 at 10:24 Comment(0)
O
4

in boot command bootcmd can have environment variable $INSTANCE_ID, you can save it for later usage. see http://cloudinit.readthedocs.org/en/latest/topics/examples.html#run-commands-on-first-boot

I for example do like below

#cloud-config
bootcmd:
  - echo $INSTANCE_ID > /hello.txt
Oconnell answered 4/11, 2014 at 14:14 Comment(0)
T
2

The closest I've seen to configurable variables is [Instance Metadata].(https://cloudinit.readthedocs.io/en/latest/topics/instancedata.html#)

It says you can use:

  • userdata provided at instance creation

You can use data created in /run/cloud-init/instance-data.json.

You can use import this instance data using Jinja templates in your YAML cloud-config to pull in this data:

## template: jinja
#cloud-config
runcmd:
    - echo 'EC2 public hostname allocated to instance: {{
      ds.meta_data.public_hostname }}' > /tmp/instance_metadata
    - echo 'EC2 availability zone: {{ v1.availability_zone }}' >>
      /tmp/instance_metadata
    - curl -X POST -d '{"hostname": "{{ds.meta_data.public_hostname }}",
      "availability-zone": "{{ v1.availability_zone }}"}'
      https://example.com

But I'm not exactly sure how you create the /run/cloud-init/instance-data.json file.

This CoreOS issue suggests that if you put variables into /etc/environment then you can use those.

I know for example that there are a few variables used such as $MIRROR $RELEASE, $INSTANCE_ID for the phone_home module.

Toccaratoccata answered 19/1, 2021 at 15:3 Comment(1)
cloud-init populates the /run/cloud-init/instance-data.json file in order to unify the data provided from the various cloud providers. The v1 entries are the safest to use, since they are where cloud-init collects common data, and the keys are guaranteed to exist.Rist
C
1

Try the ec2metadata tool (just queries the EC2 metadata). Say put the following in your instances userdata:

wget http://s3.amazonaws.com/ec2metadata/ec2-metadata
chmod u+x ec2-metadata
# The following gives you the instance id and you can pass it to your salt minion config
ec2-metadata -i

More info on the ec2-metadata script here

Cassady answered 16/12, 2013 at 19:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.