Ansible delegate_toでインベントリで定義された特定のグループを指定する

環境
Ansible
RHEL8

構文
delegate_to: 特定のグループ
インベントリで定義された特定のグループを指定します。

インベントリ

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[groupA]
172.17.101.1
172.17.101.2
[group2]
172.17.102.1
172.17.102.2
[group3]
172.17.103.1
[groupA] 172.17.101.1 172.17.101.2 [group2] 172.17.102.1 172.17.102.2 [group3] 172.17.103.1
[groupA]
172.17.101.1
172.17.101.2

[group2]
172.17.102.1
172.17.102.2

[group3]
172.17.103.1

サンプルコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
- hosts: all
become: yes
gather_facts: False
tasks:
- name: ディレクトリ作成
file:
path: /tmp/dir
state: directory
- name: ファイルのコピー
copy:
src: /etc/ansible/res.txt
dest: /tmp/dir
delegate_to: "{{ item }}"
loop: "{{ groups['groupA'] }}"
- name: ディレクトリの圧縮
archive:
path: /tmp
dest: /tmp/data.tgz
- hosts: all become: yes gather_facts: False tasks: - name: ディレクトリ作成 file: path: /tmp/dir state: directory - name: ファイルのコピー copy: src: /etc/ansible/res.txt dest: /tmp/dir delegate_to: "{{ item }}" loop: "{{ groups['groupA'] }}" - name: ディレクトリの圧縮 archive: path: /tmp dest: /tmp/data.tgz
- hosts: all
  become: yes
  gather_facts: False

  tasks:
    - name: ディレクトリ作成
      file:
        path: /tmp/dir
        state: directory

    - name: ファイルのコピー
      copy:
        src: /etc/ansible/res.txt
        dest: /tmp/dir
      delegate_to: "{{ item }}"
      loop: "{{ groups['groupA'] }}"
        
    - name: ディレクトリの圧縮
      archive:
        path: /tmp
        dest: /tmp/data.tgz

説明
「loop」ディレクティブで、インベントリで定義されたグループ『groupA』内のホストをループします。
「item」という変数には、『groupA』内のホストのIPアドレスが格納されているので、「delegate_to」の値を「item」とします。

Ansible

Posted by arkgame