Reputation: 38
I'm using ansible to provision servers on EC2, using the dynamic inventory and exact_count. This lets me scale up/down when I need to, which is nice.
Now I need to add a unique variable to the environment on each server when I provision them. One way I thought of doing this is using the inventory file like this:
[ec2-servers]
host1 myvar=abc
host2 myvar=def
...
where host1(2) somehow refer to the relevant EC2 instance, via tag_SomeName_host1 or similar.
But this doesn't tie in with how I'm currently provisioning servers. The dynamic inventory with exact_count gives me a set of identical clone servers.
Is there a way I can define servers in my inventory file, and have ansible provision it in ec2 if it doesn't exist, and remove it if a server exists in ec2 but not the inventory?
e.g.
I run my playbook for the first time with the inventory:
[ec2-servers]
host1 myvar=1
Then later I need to scale up so edit the inventory:
[ec2-servers]
host1 myvar=1
host2 myvar=2
and ansible ignores host1 as it already exists, then provisions an instance for host2.
Then later I no longer need the extra server so modify the inventory:
[ec2-servers]
host1 myvar=1
and ansible removes host2 from ec2.
Upvotes: 0
Views: 916
Reputation: 17411
No. Ansible doesn't [care to]:
You need to build the logic yourself in the playbook.
Something like, my_playbook.yml
:
- hosts: to_be_provisioned
tasks:
- include: provision_ec2_host.yml
- hosts: to_be_unprovisioned
tasks:
- include: unprovision_ec2_host.yml
both unprovision_ec2_host.yml
& provision_ec2_host.yml
should be idempotent of course.
Now you need to ensure that your inventory has correct set of hosts under the host-groups to_be_provisioned
& to_be_unprovisioned
and run my_playbook.yml.
$ cat inventory.ini
[to_be_provisioned]
host1 myvar=1
[to_be_unprovisioned]
host2 myvar=2
$ ansible-playbook -i inventory.ini my_playbook.yml
$ # modify inventory
$ cat inventory.ini
[to_be_provisioned]
host1 myvar=1
host2 myvar=2
# [to_be_unprovisioned] -- no hosts
$ ansible-playbook -i inventory.ini my_playbook.yml
$ # modify inventory
$ cat inventory.ini
[to_be_provisioned]
host1 myvar=1
[to_be_unprovisioned]
host2 myvar=2
$ ansible-playbook -i inventory.ini my_playbook.yml
Finally, to do this whole thing automatically, you can use your dynamic inventory. I recommend just make a copy of existing ec2.py
and modify it so it returns the groups as you want.
Upvotes: 0