2019年11月30日土曜日

ものぐさ playbook


このエントリーをはてなブックマークに追加


ちょっとした一発処理を Ansible で流そうとした時に、YAMLの Block Scalars(| とか > とか) と Jinja2 を組み合わせると1ファイルでいろんな処理が流せるようになるので便利です。

- hosts: localhost
  connection: local
  gather_facts: no
  vars:
    flag: false
    nodes:
      - 192.168.1.11
      - 192.168.1.12
      - 192.168.1.13
    private_key_path: /root/keypair.pem
  tasks:

    - shell: >-
        {% if flag %}
        echo "flag=true"
        {% else %}
        echo "flag=false"
        {% endif %}
      register: ret

    - debug: var=ret.stdout

    - copy:
        content: |
          [web]
          {% for i in nodes %}
          node-{{ loop.index }} ansible_host={{ i }}
          {% endfor %}
          
          [all:vars]
          ansible_user=centos
          ansible_ssh_private_key_file={{ private_key_path }}
        dest: result.txt

実行するとこんな感じ

$ ansible-playbook block_scalar.yml

PLAY [localhost] *********************************************************

TASK [shell] *************************************************************
changed: [localhost]

TASK [debug] *************************************************************
ok: [localhost] => {
    "ret.stdout": "flag=false"
}

TASK [copy] **************************************************************
changed: [localhost]

PLAY RECAP ***************************************************************
localhost : ok=3  changed=2  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0


$ cat result.txt
[web]
node-1 ansible_host=192.168.1.11
node-2 ansible_host=192.168.1.12
node-3 ansible_host=192.168.1.13

[all:vars]
ansible_user=centos
ansible_ssh_private_key_file=/root/keypair.pem

1 件のコメント:

コメントを投稿