Ansible Tip

cloud2000·2023년 9월 19일

특정 inventory group에서 정보 가져오기

inventory의 특정 group에서 host 변수 중 ip를 comma(,)로 결합하여 변수에 넣는 경우가 필요할 때가 있다. 아래 예와 같이 for과 loop.last를 체크해서 처리하면 된다.

{% for host in groups[etcd] -%}
  etcd_hosts={{ hostvars[host]['ip'] }}{%- if not loop.last -%},{%- endif -%}
{%- endfor -%}

다음 예는 hostvar의 ip변수에서 값을 가져와서 address에 저장한다. 만약 값이 없으면 기본값으로 'ansible_default_ipv4'의 주소로 셋팅한다.

address: {{ hostvars[inventory_hostname]['ip'] | default(hostvars[inventory_hostname]['ansible_default_ipv4']['address']) }}

아래는 inventory의 'etcd' 그룹에서 IP가 현재 ansible task가 실행되는 node의 IP와 동일할 경우에만 값을 설정하는 예이다.

{% set pk = groups['etcd'] %}
{% for host in pk %}
{%   if hostvars[host]['ip'] == hostvars[inventory_hostname]['ip'] %}
    - https://{{ hostvars[host]['ip'] }}:2379
{%   endif %}
{% endfor %}

ansible_fqdn, ansible_hostname, inventory_hostname 사용예

[ alt_names_etcd ]
{% if cloud_provider == 'aws' %}
DNS.1 = {{ ansible_fqdn }}
{% else %}
DNS.1 = {{ ansible_hostname }}
{% endif %}
IP.1 = 127.0.0.1
IP.2 = {{ hostvars[inventory_hostname]['ip'] | default(hostvars[inventory_hostname]['ansible_default_ipv4']['address']) }}

아래 예는 ansible script가 실행되는 node가 특정 그룹에 속해 있는지를 확인하기 위해 변수에 설정하는 예이다.

is_kube_master: "{{ inventory_hostname in groups['masters'] }}"
is_registry: "{{ inventory_hostname in groups['registry'] }}"
profile
클라우드쟁이

0개의 댓글