Attach serial number host name in Ansible etc.
クックパッドの新オフィスでitamaeによる寿司の無限プロビジョニングを体験して、Ansibleのお悩み相談してきた #infra_sushi
I saw an article called.
お悩みの詳細はスライドを見てもらうとして、一つのツールですべて賄おう
として頑張ってしまうと、構成に矛盾が出てしまうので、
適材適所で組み合わせて使わないといけないというのは、完全に正論。
I fully agree with that.
Actually, however, these two problems can be solved even with ansible. (I'm not listening to LT, so I'm sorry if I'm out of your mind)
1. Variable setting for EC2 instance creation -------------------------------------------------------------------------------------------- -------------
[webservers]
prod-web01
prod-web02
prod-web03
[webservers:vars]
ami=ami-785bae10
group_tag=web
When there is already an inventory file called
---
- hosts: webservers
gather_facts: no # noにしておくと捗る
tasks:
- local_action:
module: ec2
(パラメータは一部略しています)
instance_type: t2.micro
image: "{{ ami }}" # inventory
exact_count: 3
instance_tags:
role: "{{group_tag }}" # ここちゃんと使えます
region: us-east-1
run_once: true # 1.7以降で使えます
register: ec2
local_action so is the host to run the ansible-playbook command, no matter alone is what is written in the hosts, it will be executed in the localhost.
However, if you specify a group that contains multiple hosts, the number of modules specified by local_action will also be executed.
For this reason, introduced from 1.7 run_once use. Run_once is a parameter to make it run only on the host defined at the head of the group. Since it is local_action this time, it sounds to be executed only once on the local host.
Host name automatic number assignment
Although it is automatic numbering, I interpret it as shaking consecutive numbers here.
Numbering is with_indexed_items With, {{ item.0 }} to the index number is, {{ item.1 }} to contains the contents of the list.
- debug: msg="{{ item.1 }} at {{ item.0 }}"
with_indexed_items: some_list
I will use this.
At first I tried this,
- hostname: name="{{ host_prefix }}-{{ item.0 }}"
with_indexed_items: play_hosts
If this is the case, for example, if there are 3 units, it will be executed 9 times in total, 3 times for each 3 units.
So, the above-described run_once combine with. However, if it is simply run_once, it can only be set by one unit. Here delegate_to use.
- hostname: name="{{ host_prefix }}-{{ item.0 }}"
run_once: yes
delegate_to: "{{ item.1 }}"
with_indexed_items: play_hosts
By the way, play_hosts has entered the list of hosts to be in this play, is a pre-defined variable from the beginning.
Digression
I hate to start with 0? It's luxury.
- hostname: name="{{ host_prefix }}-{{ item.0 + 1}}"
Summary
So I showed that it can be solved ansible for two problems.
However, as you can see, it is quite tricky as you can see, so we agree that it is better to combine at the right place.
Publicity
ツキノワ In, we are planning a paid seminar of ansible (with hands-on).
If you are interested please contact us from the web page.