Ansible 範例

搭配 Ansible SSH 容器 使用的最小可執行範例:一份 Playbook、兩種 inventory 寫法,以及一個當作目標節點的 Dockerfile。

Inventory:單一檔案

host.cfg 直接把三個 Docker 容器與一台額外主機寫在同一份 inventory:

[servers]
docker1 ansible_ssh_host=127.0.0.1 ansible_ssh_port=32769 ansible_ssh_user=root
docker2 ansible_ssh_host=127.0.0.1 ansible_ssh_port=32770 ansible_ssh_user=root
docker3 ansible_ssh_host=127.0.0.1 ansible_ssh_port=32771 ansible_ssh_user=root
[g1]
g1 ansible_ssh_host=127.0.0.1 ansible_ssh_port=32769 ansible_ssh_user=root

ansible_ssh_port 要換成 docker port <container> 22 實際回報的 port。

Inventory:目錄拆分

test.cfgansible.cfg 形式的設定,把 inventory 指到一個目錄:

[default]
inventory = ./host/

host/ 目錄下每個檔案是一個群組來源:

Ansible 會把目錄裡所有檔案合併成一份 inventory,適合節點多、想按用途分檔管理的情境。

Playbook

---
- name: say 'hello world'
  hosts: all
  task:
    - name: echo 'hello world'
      command: echo 'hello'
      register: result

    - name: print stdout
      debug:
        msg: ""

原始檔 playbook.yml 使用 tab 縮排,且關鍵字寫成 task。實際執行前需改成空白縮排並改為 tasks,否則 Ansible 會回報解析錯誤。上面的版本已修正縮排,task 拼字請一併改成 tasks

目標節點 Dockerfile

docker/Dockerfile 是一個裝好 sshdansible 的 CentOS 7 節點:

FROM centos:7
RUN yum -y install openssh-server;yum clean all
RUN mkdir /var/run/sshd
RUN ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key
RUN ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key
RUN /bin/echo 'root:root'|chpasswd
RUN /bin/sed -i 's/.*session.*required.*pam_loginuid.so.*/session optional pam_loginuid.so/g' /etc/pam.d/sshd
RUN /bin/echo -e "LANG=\"en_US.UTF-8\"" > /etc/default/local
RUN yum install -y epel-release
RUN yum install -y ansible
EXPOSE 22
CMD /usr/sbin/sshd -D

執行

# 連線測試
ansible -i host.cfg all -m ping

# 執行 Playbook
ansible-playbook -i host.cfg playbook.yml

# 只檢查不實際執行
ansible-playbook -i host.cfg playbook.yml --check

← 回到 DevOps

本目錄檔案