ansible的劇本

ansible的playbook的介紹-yaml

ansible的playbook是使用yaml語言寫的php

YAML標記語言介紹
YAML是一個可讀性高的用來表達資料序列的格式。YAML參考了其餘多種語言包括XML、C語言、Python、Perl以及電子郵件格式RFC2822等。Clark Evans在2001年在首次發表了這種語言另外Ingy dtNet與Oren Ben-Kiki也是這語言的共同設計者。 
YAML Ain't Markup Language即YAML不是XML。不過在開發的這種語言時YAML的意思實際上是"Yet Another Markup Language"還是一種標記語言。其特性 
YAML的可讀性好 
YAML和腳本語言的交互性好 
YAML使用實現語言的數據類型 
YAML有一個一致的信息模型 
YAML易於實現 
YAML能夠基於流來處理 
YAML表達能力強擴展性好 


它的基本語法規則以下。
• 大小寫敏感
• 使用縮進表示層級關係
• 縮進時不容許使用Tab鍵,只容許使用空格。
• 縮進的空格數目不重要,只要相同層級的元素左側對齊便可

# 表示註釋,從這個字符一直到行尾,都會被解析器忽略。html

yaml支持的數據類型

對象:
對象的一組鍵值對,使用冒號結構表示。
my_key: my_value

數組:
數據結構的子成員是一個數組,則能夠在該項下面縮進一個空格
languages:
- python
- perl
- rubynode


純量
純量是最基本的、不可再分的值
字符串
var: abc
布爾值
var: true
整數
var: 123
浮點數
var: 12.30
Null
var: ~
時間
time: 2001-12-14
日期
date 20:10:20


 當須要執行的任務有多個時,須要一條一條編輯ansible命令,而後執行,並且當須要重複執行時,又要從新編輯執行,這樣效率不高,所以ansible就能夠利用playbook來完成將任務寫到一個YAML格式的文件中,而後利用ansible-playbook進行調用該文件,從而實現了多條語句,可重複執行的效果,相似shell腳本的效果,ansible的playbook要藉助YAML文件來實現,YAML文件擴展名一般爲.yaml或.ymlpython

 

使用playbook的基本命令格式

Usage: ansible-playbook [options] playbook.yml [playbook2 ...]
-C, --check 幹跑一次 不會真正落地
-f FORKS 作高併發
--list-hosts 列出匹配的主機
--syntax-check 檢查語法

playbook的基礎組件

hosts:運行指定任務的目標主機,多個主機用:冒號分隔
remote_user:在遠程主機上執行任務的用戶;能夠全局指定,也能夠單個任務指定,若是是root用戶執行能夠不用寫,默認是root
sudo_user:表示以sudo方式運行任務時,切換爲哪一個用戶身份運行
tasks: 任務列表

使用palybook來管理被控機

1 建立劇本

編寫ansible的劇本,建立yaml語言的文件,文件的位置能夠任意,爲了規範,好記,最好有一個單獨的目錄存放劇本mysql

我建立了mkdir /palybook這個目錄來存在劇本linux

:後綴名是.yaml 或 ymlios


[root@master ~]# vim p1.yml web

- hosts: web
  remote_user: root
  tasks:
  - name: add group
    group: name=IT
  - name: creat user
    user: name=alex20
- hosts: 192.168.16.140
  remote_user: root
  tasks:
  - name: copy
    copy: src=/var/log/yum.log dest=/tmp/

文件翻譯成python的語言的格式redis

文件的解釋:sql

- hosts: web  # 應用的主機 web是主機組
  remote_user: root # 使用root來執行這個playbook
  tasks: # 要執行的任務
  - name: add group  # 任務的名字,能夠隨意寫
    group: name=IT  # group 是執行的模塊名 後面是模塊的參數
  - name: creat user # 任務的名字
    user: name=alex20 # 使用user模塊建立用戶 alex20
- hosts: 192.168.16.140 # 140這臺主機執行下面的命令
  remote_user: root # root用戶執行
  tasks: # 執行任務
  - name: copy # 任務的名字
    copy: src=/var/log/yum.log dest=/tmp/ # 使用copy模塊來複制文件
p1.yml

 

執行playbook

1 測試p1.yml的語法是否正確

[root@master ~]#ansible-playbook --syntax-check p1.yml

2 測試執行
[root@master ~]# ansible-playbook --check p1.yml
3 運行
[root@master ~]# ansible-playbook p1.yml

- hosts: web
  remote_user: root
  tasks:
  - name: add group
    group: name=IT
  - name: creat user
    user: name=alex20
- hosts: 192.168.16.140
  remote_user: root
  tasks:
  - name: copy
    copy: src=/var/log/yum.log dest=/tmp/
[root@bogon palybook]# ansible-playbook p1.yml

PLAY [web] *********************************************************************************************

TASK [Gathering Facts] *********************************************************************************
ok: [192.168.16.138]
ok: [192.168.16.139]

TASK [add group] ***************************************************************************************
ok: [192.168.16.139]
ok: [192.168.16.138]

TASK [creat user] **************************************************************************************
ok: [192.168.16.139]
ok: [192.168.16.138]

PLAY [192.168.16.140] **********************************************************************************

TASK [Gathering Facts] *********************************************************************************
ok: [192.168.16.140]

TASK [copy] ********************************************************************************************
ok: [192.168.16.140]

PLAY RECAP *********************************************************************************************
192.168.16.138             : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0 ignored=0
192.168.16.139             : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0 ignored=0
192.168.16.140             : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0 ignored=0
View Code

 

 

劇本局用冪等性 : 冪等性 無論執行多少次,等到的結果都是同樣的

2 劇本的傳參- 5種方式

編寫playbook

[root@bogon palybook]# cat p2.yml
- hosts: web
  remote_user: root
  tasks:
   - name: create{{user}}
     user: name={{user}}
cat p2.yml

 

2.1  在命令行中使用-e 傳參:

ansible-playbook  -e user=alex21 p2.yml 

PLAY [web] *********************************************************************************************

TASK [Gathering Facts] *********************************************************************************
ok: [192.168.16.138]
ok: [192.168.16.139]

TASK [createalex21] ************************************************************************************
changed: [192.168.16.139]
changed: [192.168.16.138]

PLAY RECAP *********************************************************************************************
192.168.16.138             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0 ignored=0
192.168.16.139             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0 ignored=0
ansible-playbook -e user=alex21 p2.yml

 

在web主機組上查看用戶alex1建立成功

2.2 在hosts文件中實現傳參

編寫vim /etc/ansible/hosts文件

[web]
192.168.16.138 user=alex23
192.168.16.139 user=alex24
vim /etc/ansible/hosts

 

ansible-playbook   p2.yml

PLAY [web] *********************************************************************************************

TASK [Gathering Facts] *********************************************************************************
ok: [192.168.16.139]
ok: [192.168.16.138]

TASK [createalex23] ************************************************************************************
changed: [192.168.16.139]
changed: [192.168.16.138]

PLAY RECAP *********************************************************************************************
192.168.16.138             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0 ignored=0
192.168.16.139             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0 ignored=0
ansible-playbook p2.yml

 

在被控節點發如今138上建立alex23

在被控節點發如今138上建立alex24

2.3 編寫vim /etc/ansible/hosts文件

 

[web]
192.168.16.138
192.168.16.139
[web:vars]
user=alex25

 

ansible-playbook   p2.yml

 

PLAY [web] *********************************************************************************************

TASK [Gathering Facts] *********************************************************************************
ok: [192.168.16.138]
ok: [192.168.16.139]

TASK [createalex25] ************************************************************************************
changed: [192.168.16.138]
changed: [192.168.16.139]

PLAY RECAP *********************************************************************************************
192.168.16.138             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0 ignored=0
192.168.16.139             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0 ignored=0
ansible-playbook p2.yml

 

在被控節點上建立alex25的用戶

2.4 在palybook中傳參

 編寫playbook

 

- hosts: web
  vars:
   - user: alex26
  remote_user: root
  tasks:
   - name: create{{user}}
     user: name={{user}}

 

ansible-playbook  p2.yml

PLAY [web] *********************************************************************************************

TASK [Gathering Facts] *********************************************************************************
ok: [192.168.16.139]
ok: [192.168.16.138]

TASK [createalex26] ************************************************************************************
changed: [192.168.16.139]
changed: [192.168.16.138]

PLAY RECAP *********************************************************************************************
192.168.16.138             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0 ignored=0
192.168.16.139             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0 ignored=0
ansible-playbook p2.yml

在被控節點上建立 alex26

2.5 利用 register傳參

 使用registe以前先看一個例子

 編寫playbook. p3.yml

[root@bogon palybook]# cat p3.yml
- hosts: web
  remote_user: root
  tasks:
  - name: yum
    yum: name=bc
  - name: sum
    shell: echo "4+2"| bc
    register: he
  - name: echo
    shell: echo {{he}} > /tmp/sum.txt
cat p3.yml

在被控機上能夠看到,是字典形式的,前面都有u 這是表明unicode

 

cat sum.txt
{stderr_lines: [], uchanged: True, uend: u2019-07-17 14:47:59.209104, failed: False, ustdout: u6, ucmd:uecho "4+2"| bc, urc: 0, ustart: u2019-07-17 14:47:59.204147, ustderr: u, udelta: u0:00:00.004957, stdout_lines: [u6]}

 

正確的寫法:

 編寫playbook. p3.yml

 

[root@bogon palybook]# cat p3.yml
- hosts: web
  remote_user: root
  tasks:
  - name: yum
    yum: name=bc
  - name: sum
    shell: echo "4+2"| bc
    register: he
  - name: echo
    shell: echo {{he.stdout}} > /tmp/sum.txt

 

被控機:

[root@bogon tmp]# cat sum.txt
6

 使用register建立用戶alex27

[root@bogon palybook]# cat p4.yml
- hosts: web
  remote_user: root
  tasks:
  - name: yum
    yum: name=bc
  - name: sum
    shell: echo "25+2"| bc
    register: user
  - name: add user{{user.stdout}}
    user: name=alex{{user.stdout}}
cat p4.yml

 

ansible-playbook  p4.yml

 總結: 傳參的優先級

-e > playbook > hosts 文件

3 使用tag

tag使用標記執行的模塊的,能夠選擇單獨執行某一個模塊

現有 p5.yml 的文件,已知在被控節點上,已經安裝好了,redis軟件,若是咱們執行copy模塊來把主控節點的# ceshi

文件拷貝到被控節點上/etc/redis.conf上,

咱們可使用tag是執行copy 模塊

[root@bogon palybook]# cat p5.yml
- hosts: web
  remote_user: root
  tasks:
   - name: install redis
     yum: name=redis
   - name: copy
     copy: src=/etc/redis.conf dest=/etc/redis.conf
   - name: service redis start
     service: name=redis state=started

具體的寫法

1 我在節點的//etc/redis.conf 文件的最後添加了 # ceshi 來檢驗,copy模塊是否成功
若是多個模塊有tags標籤,.想運行多個模塊,能夠用逗號將tags名字分開
ansible-playbook -t copyfile p5.yml

PLAY [web] *********************************************************************************************

TASK [Gathering Facts] *********************************************************************************
ok: [192.168.16.139]
ok: [192.168.16.138]

TASK [copy] ********************************************************************************************
changed: [192.168.16.139]
changed: [192.168.16.138]

PLAY RECAP *********************************************************************************************
192.168.16.138             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0 ignored=0
192.168.16.139             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0 ignored=0
ansible-playbook -t copyfile p5.yml

 從運行的結果中能夠看出只運行了 copy模塊

在被控節點上:看到,說明copy成功

[root@bogon tmp]# tail -1 /etc/redis.conf
# ceshi
 

4 補充模塊:setup

 用來收集被控端主機的信息:

ansible 192.168.16.169 -m setup

192.168.16.138 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "192.168.16.138"
        ],
        "ansible_all_ipv6_addresses": [],
        "ansible_apparmor": {
            "status": "disabled"
        },
        "ansible_architecture": "x86_64",
        "ansible_bios_date": "07/31/2013",
        "ansible_bios_version": "6.00",
        "ansible_cmdline": {
            "BOOT_IMAGE": "/vmlinuz-3.10.0-327.el7.x86_64",
            "LANG": "en_US.UTF-8",
            "crashkernel": "auto",
            "quiet": true,
            "rd.lvm.lv": "centos/swap",
            "rhgb": true,
            "ro": true,
            "root": "/dev/mapper/centos-root"
        },
        "ansible_date_time": {
            "date": "2019-07-17",
            "day": "17",
            "epoch": "1563348992",
            "hour": "15",
            "iso8601": "2019-07-17T07:36:32Z",
            "iso8601_basic": "20190717T153632604168",
            "iso8601_basic_short": "20190717T153632",
            "iso8601_micro": "2019-07-17T07:36:32.604252Z",
            "minute": "36",
            "month": "07",
            "second": "32",
            "time": "15:36:32",
            "tz": "CST",
            "tz_offset": "+0800",
            "weekday": "Wednesday",
            "weekday_number": "3",
            "weeknumber": "28",
            "year": "2019"
        },
        "ansible_default_ipv4": {
            "address": "192.168.16.138",
            "alias": "eno16777736",
            "broadcast": "192.168.16.255",
            "gateway": "192.168.16.2",
            "interface": "eno16777736",
            "macaddress": "00:0c:29:ba:8f:d2",
            "mtu": 1500,
            "netmask": "255.255.255.0",
            "network": "192.168.16.0",
            "type": "ether"
        },
        "ansible_default_ipv6": {},
        "ansible_device_links": {
            "ids": {
                "dm-0": [
                    "dm-name-centos-root",
                    "dm-uuid-LVM-122vaa2zigMi2y4jShiO0EFiCfRG0imyrXbbOGLi9aszGNyoVKnK0m4fBF3NclZH"
                ],
                "dm-1": [
                    "dm-name-centos-swap",
                    "dm-uuid-LVM-122vaa2zigMi2y4jShiO0EFiCfRG0imyiUq0NKSuO7SQHoEQMcGOaZ6JPI4yhzgR"
                ],
                "sda2": [
                    "lvm-pv-uuid-vraMCf-JSqM-a2Uo-onaI-cVS5-3YJX-x5R6F2"
                ],
                "sr0": [
                    "ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001"
                ]
            },
            "labels": {
                "sr0": [
                    "CentOS\\x207\\x20x86_64"
                ]
            },
            "masters": {
                "sda2": [
                    "dm-0",
                    "dm-1"
                ]
            },
            "uuids": {
                "dm-0": [
                    "47577089-a032-4e19-9648-878f5330e70d"
                ],
                "dm-1": [
                    "a6a9dfb6-b70c-43bc-81c3-4281b8a8df46"
                ],
                "sda1": [
                    "ae1ee2e5-f71c-4bb7-822e-01e5f145592e"
                ],
                "sr0": [
                    "2015-12-09-23-14-10-00"
                ]
            }
        },
        "ansible_devices": {
            "dm-0": {
                "holders": [],
                "host": "",
                "links": {
                    "ids": [
                        "dm-name-centos-root",
                        "dm-uuid-LVM-122vaa2zigMi2y4jShiO0EFiCfRG0imyrXbbOGLi9aszGNyoVKnK0m4fBF3NclZH"
                    ],
                    "labels": [],
                    "masters": [],
                    "uuids": [
                        "47577089-a032-4e19-9648-878f5330e70d"
                    ]
                },
                "model": null,
                "partitions": {},
                "removable": "0",
                "rotational": "1",
                "sas_address": null,
                "sas_device_handle": null,
                "scheduler_mode": "",
                "sectors": "36634624",
                "sectorsize": "512",
                "size": "17.47 GB",
                "support_discard": "0",
                "vendor": null,
                "virtual": 1
            },
            "dm-1": {
                "holders": [],
                "host": "",
                "links": {
                    "ids": [
                        "dm-name-centos-swap",
                        "dm-uuid-LVM-122vaa2zigMi2y4jShiO0EFiCfRG0imyiUq0NKSuO7SQHoEQMcGOaZ6JPI4yhzgR"
                    ],
                    "labels": [],
                    "masters": [],
                    "uuids": [
                        "a6a9dfb6-b70c-43bc-81c3-4281b8a8df46"
                    ]
                },
                "model": null,
                "partitions": {},
                "removable": "0",
                "rotational": "1",
                "sas_address": null,
                "sas_device_handle": null,
                "scheduler_mode": "",
                "sectors": "4194304",
                "sectorsize": "512",
                "size": "2.00 GB",
                "support_discard": "0",
                "vendor": null,
                "virtual": 1
            },
            "fd0": {
                "holders": [],
                "host": "",
                "links": {
                    "ids": [],
                    "labels": [],
                    "masters": [],
                    "uuids": []
                },
                "model": null,
                "partitions": {},
                "removable": "1",
                "rotational": "1",
                "sas_address": null,
                "sas_device_handle": null,
                "scheduler_mode": "deadline",
                "sectors": "8",
                "sectorsize": "512",
                "size": "4.00 KB",
                "support_discard": "0",
                "vendor": null,
                "virtual": 1
            },
            "sda": {
                "holders": [],
                "host": "",
                "links": {
                    "ids": [],
                    "labels": [],
                    "masters": [],
                    "uuids": []
                },
                "model": "VMware Virtual S",
                "partitions": {
                    "sda1": {
                        "holders": [],
                        "links": {
                            "ids": [],
                            "labels": [],
                            "masters": [],
                            "uuids": [
                                "ae1ee2e5-f71c-4bb7-822e-01e5f145592e"
                            ]
                        },
                        "sectors": "1024000",
                        "sectorsize": 512,
                        "size": "500.00 MB",
                        "start": "2048",
                        "uuid": "ae1ee2e5-f71c-4bb7-822e-01e5f145592e"
                    },
                    "sda2": {
                        "holders": [
                            "centos-root",
                            "centos-swap"
                        ],
                        "links": {
                            "ids": [
                                "lvm-pv-uuid-vraMCf-JSqM-a2Uo-onaI-cVS5-3YJX-x5R6F2"
                            ],
                            "labels": [],
                            "masters": [
                                "dm-0",
                                "dm-1"
                            ],
                            "uuids": []
                        },
                        "sectors": "40916992",
                        "sectorsize": 512,
                        "size": "19.51 GB",
                        "start": "1026048",
                        "uuid": null
                    }
                },
                "removable": "0",
                "rotational": "1",
                "sas_address": null,
                "sas_device_handle": null,
                "scheduler_mode": "deadline",
                "sectors": "41943040",
                "sectorsize": "512",
                "size": "20.00 GB",
                "support_discard": "0",
                "vendor": "VMware,",
                "virtual": 1
            },
            "sr0": {
                "holders": [],
                "host": "",
                "links": {
                    "ids": [
                        "ata-VMware_Virtual_IDE_CDROM_Drive_10000000000000000001"
                    ],
                    "labels": [
                        "CentOS\\x207\\x20x86_64"
                    ],
                    "masters": [],
                    "uuids": [
                        "2015-12-09-23-14-10-00"
                    ]
                },
                "model": "VMware IDE CDR10",
                "partitions": {},
                "removable": "1",
                "rotational": "1",
                "sas_address": null,
                "sas_device_handle": null,
                "scheduler_mode": "cfq",
                "sectors": "8456192",
                "sectorsize": "2048",
                "size": "4.03 GB",
                "support_discard": "0",
                "vendor": "NECVMWar",
                "virtual": 1
            }
        },
        "ansible_distribution": "CentOS",
        "ansible_distribution_file_parsed": true,
        "ansible_distribution_file_path": "/etc/redhat-release",
        "ansible_distribution_file_variety": "RedHat",
        "ansible_distribution_major_version": "7",
        "ansible_distribution_release": "Core",
        "ansible_distribution_version": "7",
        "ansible_dns": {
            "nameservers": [
                "192.168.16.2"
            ]
        },
        "ansible_domain": "",
        "ansible_effective_group_id": 0,
        "ansible_effective_user_id": 0,
        "ansible_eno16777736": {
            "active": true,
            "device": "eno16777736",
            "features": {
                "busy_poll": "off [fixed]",
                "fcoe_mtu": "off [fixed]",
                "generic_receive_offload": "on",
                "generic_segmentation_offload": "on",
                "highdma": "off [fixed]",
                "large_receive_offload": "off [fixed]",
                "loopback": "off [fixed]",
                "netns_local": "off [fixed]",
                "ntuple_filters": "off [fixed]",
                "receive_hashing": "off [fixed]",
                "rx_all": "off",
                "rx_checksumming": "off",
                "rx_fcs": "off",
                "rx_vlan_filter": "on [fixed]",
                "rx_vlan_offload": "on",
                "rx_vlan_stag_filter": "off [fixed]",
                "rx_vlan_stag_hw_parse": "off [fixed]",
                "scatter_gather": "on",
                "tcp_segmentation_offload": "on",
                "tx_checksum_fcoe_crc": "off [fixed]",
                "tx_checksum_ip_generic": "on",
                "tx_checksum_ipv4": "off [fixed]",
                "tx_checksum_ipv6": "off [fixed]",
                "tx_checksum_sctp": "off [fixed]",
                "tx_checksumming": "on",
                "tx_fcoe_segmentation": "off [fixed]",
                "tx_gre_segmentation": "off [fixed]",
                "tx_gso_robust": "off [fixed]",
                "tx_ipip_segmentation": "off [fixed]",
                "tx_lockless": "off [fixed]",
                "tx_mpls_segmentation": "off [fixed]",
                "tx_nocache_copy": "off",
                "tx_scatter_gather": "on",
                "tx_scatter_gather_fraglist": "off [fixed]",
                "tx_sit_segmentation": "off [fixed]",
                "tx_tcp6_segmentation": "off [fixed]",
                "tx_tcp_ecn_segmentation": "off [fixed]",
                "tx_tcp_segmentation": "on",
                "tx_udp_tnl_segmentation": "off [fixed]",
                "tx_vlan_offload": "on [fixed]",
                "tx_vlan_stag_hw_insert": "off [fixed]",
                "udp_fragmentation_offload": "off [fixed]",
                "vlan_challenged": "off [fixed]"
            },
            "hw_timestamp_filters": [],
            "ipv4": {
                "address": "192.168.16.138",
                "broadcast": "192.168.16.255",
                "netmask": "255.255.255.0",
                "network": "192.168.16.0"
            },
            "macaddress": "00:0c:29:ba:8f:d2",
            "module": "e1000",
            "mtu": 1500,
            "pciid": "0000:02:01.0",
            "promisc": false,
            "speed": 1000,
            "timestamping": [
                "tx_software",
                "rx_software",
                "software"
            ],
            "type": "ether"
        },
        "ansible_env": {
            "HOME": "/root",
            "LANG": "en_US.UTF-8",
            "LESSOPEN": "||/usr/bin/lesspipe.sh %s",
            "LOGNAME": "root",
            "MAIL": "/var/mail/root",
            "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin",
            "PWD": "/root",
            "SHELL": "/bin/bash",
            "SHLVL": "2",
            "SSH_CLIENT": "192.168.16.137 60835 22",
            "SSH_CONNECTION": "192.168.16.137 60835 192.168.16.138 22",
            "SSH_TTY": "/dev/pts/2",
            "TERM": "xterm",
            "USER": "root",
            "XDG_RUNTIME_DIR": "/run/user/0",
            "XDG_SESSION_ID": "23",
            "_": "/usr/bin/python"
        },
        "ansible_fibre_channel_wwn": [],
        "ansible_fips": false,
        "ansible_form_factor": "Other",
        "ansible_fqdn": "bogon",
        "ansible_hostname": "bogon",
        "ansible_hostnqn": "",
        "ansible_interfaces": [
            "lo",
            "eno16777736"
        ],
        "ansible_is_chroot": false,
        "ansible_iscsi_iqn": "",
        "ansible_kernel": "3.10.0-327.el7.x86_64",
        "ansible_lo": {
            "active": true,
            "device": "lo",
            "features": {
                "busy_poll": "off [fixed]",
                "fcoe_mtu": "off [fixed]",
                "generic_receive_offload": "on",
                "generic_segmentation_offload": "on",
                "highdma": "on [fixed]",
                "large_receive_offload": "off [fixed]",
                "loopback": "on [fixed]",
                "netns_local": "on [fixed]",
                "ntuple_filters": "off [fixed]",
                "receive_hashing": "off [fixed]",
                "rx_all": "off [fixed]",
                "rx_checksumming": "on [fixed]",
                "rx_fcs": "off [fixed]",
                "rx_vlan_filter": "off [fixed]",
                "rx_vlan_offload": "off [fixed]",
                "rx_vlan_stag_filter": "off [fixed]",
                "rx_vlan_stag_hw_parse": "off [fixed]",
                "scatter_gather": "on",
                "tcp_segmentation_offload": "on",
                "tx_checksum_fcoe_crc": "off [fixed]",
                "tx_checksum_ip_generic": "on [fixed]",
                "tx_checksum_ipv4": "off [fixed]",
                "tx_checksum_ipv6": "off [fixed]",
                "tx_checksum_sctp": "off [fixed]",
                "tx_checksumming": "on",
                "tx_fcoe_segmentation": "off [fixed]",
                "tx_gre_segmentation": "off [fixed]",
                "tx_gso_robust": "off [fixed]",
                "tx_ipip_segmentation": "off [fixed]",
                "tx_lockless": "on [fixed]",
                "tx_mpls_segmentation": "off [fixed]",
                "tx_nocache_copy": "off [fixed]",
                "tx_scatter_gather": "on [fixed]",
                "tx_scatter_gather_fraglist": "on [fixed]",
                "tx_sit_segmentation": "off [fixed]",
                "tx_tcp6_segmentation": "on",
                "tx_tcp_ecn_segmentation": "on",
                "tx_tcp_segmentation": "on",
                "tx_udp_tnl_segmentation": "off [fixed]",
                "tx_vlan_offload": "off [fixed]",
                "tx_vlan_stag_hw_insert": "off [fixed]",
                "udp_fragmentation_offload": "on",
                "vlan_challenged": "on [fixed]"
            },
            "hw_timestamp_filters": [],
            "ipv4": {
                "address": "127.0.0.1",
                "broadcast": "host",
                "netmask": "255.0.0.0",
                "network": "127.0.0.0"
            },
            "ipv6": [
                {
                    "address": "::1",
                    "prefix": "128",
                    "scope": "host"
                }
            ],
            "mtu": 65536,
            "promisc": false,
            "timestamping": [
                "rx_software",
                "software"
            ],
            "type": "loopback"
        },
        "ansible_local": {},
        "ansible_lsb": {},
        "ansible_lvm": {
            "lvs": {
                "root": {
                    "size_g": "17.47",
                    "vg": "centos"
                },
                "swap": {
                    "size_g": "2.00",
                    "vg": "centos"
                }
            },
            "pvs": {
                "/dev/sda2": {
                    "free_g": "0.04",
                    "size_g": "19.51",
                    "vg": "centos"
                }
            },
            "vgs": {
                "centos": {
                    "free_g": "0.04",
                    "num_lvs": "2",
                    "num_pvs": "1",
                    "size_g": "19.51"
                }
            }
        },
        "ansible_machine": "x86_64",
        "ansible_machine_id": "081f932dd7fb4b96a333f27e0f3928de",
        "ansible_memfree_mb": 629,
        "ansible_memory_mb": {
            "nocache": {
                "free": 835,
                "used": 150
            },
            "real": {
                "free": 629,
                "total": 985,
                "used": 356
            },
            "swap": {
                "cached": 0,
                "free": 2047,
                "total": 2047,
                "used": 0
            }
        },
        "ansible_memtotal_mb": 985,
        "ansible_mounts": [
            {
                "block_available": 95343,
                "block_size": 4096,
                "block_total": 127147,
                "block_used": 31804,
                "device": "/dev/sda1",
                "fstype": "xfs",
                "inode_available": 511670,
                "inode_total": 512000,
                "inode_used": 330,
                "mount": "/boot",
                "options": "rw,relatime,attr2,inode64,noquota",
                "size_available": 390524928,
                "size_total": 520794112,
                "uuid": "ae1ee2e5-f71c-4bb7-822e-01e5f145592e"
            },
            {
                "block_available": 4173596,
                "block_size": 4096,
                "block_total": 4576768,
                "block_used": 403172,
                "device": "/dev/mapper/centos-root",
                "fstype": "xfs",
                "inode_available": 18259518,
                "inode_total": 18317312,
                "inode_used": 57794,
                "mount": "/",
                "options": "rw,relatime,attr2,inode64,noquota",
                "size_available": 17095049216,
                "size_total": 18746441728,
                "uuid": "47577089-a032-4e19-9648-878f5330e70d"
            }
        ],
        "ansible_nodename": "bogon",
        "ansible_os_family": "RedHat",
        "ansible_pkg_mgr": "yum",
        "ansible_proc_cmdline": {
            "BOOT_IMAGE": "/vmlinuz-3.10.0-327.el7.x86_64",
            "LANG": "en_US.UTF-8",
            "crashkernel": "auto",
            "quiet": true,
            "rd.lvm.lv": [
                "centos/root",
                "centos/swap"
            ],
            "rhgb": true,
            "ro": true,
            "root": "/dev/mapper/centos-root"
        },
        "ansible_processor": [
            "0",
            "GenuineIntel",
            "Intel(R) Core(TM) i5-4200M CPU @ 2.50GHz"
        ],
        "ansible_processor_cores": 1,
        "ansible_processor_count": 1,
        "ansible_processor_threads_per_core": 1,
        "ansible_processor_vcpus": 1,
        "ansible_product_name": "VMware Virtual Platform",
        "ansible_product_serial": "VMware-56 4d 95 3c 07 3c 26 00-1c 3c 27 56 a2 ba 8f d2",
        "ansible_product_uuid": "564D953C-073C-2600-1C3C-2756A2BA8FD2",
        "ansible_product_version": "None",
        "ansible_python": {
            "executable": "/usr/bin/python",
            "has_sslcontext": true,
            "type": "CPython",
            "version": {
                "major": 2,
                "micro": 5,
                "minor": 7,
                "releaselevel": "final",
                "serial": 0
            },
            "version_info": [
                2,
                7,
                5,
                "final",
                0
            ]
        },
        "ansible_python_version": "2.7.5",
        "ansible_real_group_id": 0,
        "ansible_real_user_id": 0,
        "ansible_selinux": {
            "status": "disabled"
        },
        "ansible_selinux_python_present": true,
        "ansible_service_mgr": "systemd",
        "ansible_ssh_host_key_ecdsa_public": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBAIq8nwF4vJxd4021uQqf5zq97+bHlmOyMgre4fRvbfTqN0c04W8jI0Nekxw+l3cJh8nhefcAzAJjhbKebK7Ndc=",
        "ansible_ssh_host_key_ed25519_public": "AAAAC3NzaC1lZDI1NTE5AAAAIBQ4Ae+rq830BkdOrn/FcZ3ZLhntv7nYPniwU4K7qmnH",
        "ansible_ssh_host_key_rsa_public": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDoT4LU9LSj0whFKHRtdXL/Y9hgHCqafBn0LqPJy/Am+rXjHkGWmvC/JrhgYNk931vYiOT77KbreSpFEvumFAnr+MnyTVNnJuCLO7tgA9IvINF+Y/JwWoVobQj8vYIz0PBzDsiLSF8iGZyNcPQJFYjyh4cZqWSyo3PZxhghVIVjfcaZM9bVHvy2W7Vbh5GqCQRkkjEl5DkR+wlX+6t1MBRohTPms8VGbhpO4jI9YJtOcKGacjHoQN869Hk7X44sgPYgC41WTcJLmhba6Vkcx6z61wA0tKifvKODfMqm3VLiEOtL4Sb0oIu5Iw+VUYDEddQ8vJWRca4LjI8odsE92tDB",
        "ansible_swapfree_mb": 2047,
        "ansible_swaptotal_mb": 2047,
        "ansible_system": "Linux",
        "ansible_system_capabilities": [
            "cap_chown",
            "cap_dac_override",
            "cap_dac_read_search",
            "cap_fowner",
            "cap_fsetid",
            "cap_kill",
            "cap_setgid",
            "cap_setuid",
            "cap_setpcap",
            "cap_linux_immutable",
            "cap_net_bind_service",
            "cap_net_broadcast",
            "cap_net_admin",
            "cap_net_raw",
            "cap_ipc_lock",
            "cap_ipc_owner",
            "cap_sys_module",
            "cap_sys_rawio",
            "cap_sys_chroot",
            "cap_sys_ptrace",
            "cap_sys_pacct",
            "cap_sys_admin",
            "cap_sys_boot",
            "cap_sys_nice",
            "cap_sys_resource",
            "cap_sys_time",
            "cap_sys_tty_config",
            "cap_mknod",
            "cap_lease",
            "cap_audit_write",
            "cap_audit_control",
            "cap_setfcap",
            "cap_mac_override",
            "cap_mac_admin",
            "cap_syslog",
            "35",
            "36+ep"
        ],
        "ansible_system_capabilities_enforced": "True",
        "ansible_system_vendor": "VMware, Inc.",
        "ansible_uptime_seconds": 25300,
        "ansible_user_dir": "/root",
        "ansible_user_gecos": "root",
        "ansible_user_gid": 0,
        "ansible_user_id": "root",
        "ansible_user_shell": "/bin/bash",
        "ansible_user_uid": 0,
        "ansible_userspace_architecture": "x86_64",
        "ansible_userspace_bits": "64",
        "ansible_virtualization_role": "guest",
        "ansible_virtualization_type": "VMware",
        "discovered_interpreter_python": "/usr/bin/python",
        "gather_subset": [
            "all"
        ],
        "module_setup": true
    },
    "changed": false
}
ansible 192.168.16.138 -m setup

 

 參數說明:

ansible_all_ipv4_addresses #ipv4的全部地址
ansible_all_ipv6_addresses #ipv6的全部地址
ansible_architecture #系統的架構
ansible_bios_date #bios的出廠時間
ansible_bios_version #bios的版本
ansible_date_time #系統時間
ansible_default_ipv4 #系統的默認ipv4地址
ansible_default_ipv6 #系統默認的ipv6地址
ansible_distribution #系統的名稱
ansible_distribution_major_version #系統的主版本號
ansible_dns #系統dns
ansible_env #系統環境
ansible_kernel #系統內核版本
ansible_machine #系統架構
ansible_memtotal_mb #系統的內存大小
ansible_os_family #系統的家族
ansible_pkg_mgr #系統包的管理工具
ansible_nodename #系統主機名
ansible_processor_cores #每顆cpu上的核心數
ansible_processor_count #cpu的顆數
ansible_processor_vcpus #cpu的總數= 顆數*核數 ansible_python #python版本 ansible_system #系統

template模塊補充

template 和copy的模塊的功能同樣 ,都是向遠程主機上傳送文件的,能夠copy是送的是原封不動的文件,template 能夠將文件中的變量渲染出來

現有以下的文件,咱們想把/etc/redis.conf 文件 傳到遠程的主機上,但/etc/redis.conf 問bind 的ip 是遠程主機的ip,這時須要使用 template

[root@bogon palybook]# cat p5.yml - hosts: web remote_user: root tasks: - name: copy copy: src=/etc/redis.conf dest=/etc/redis.conf - name: service redis start service: name=redis state=started

看主機的ip

ansible 192.168.16.139 -m setup -a "filter=*ipv4*"

192.168.16.139 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "192.168.16.139"
        ],
        "ansible_default_ipv4": {
            "address": "192.168.16.139",
            "alias": "eno16777736",
            "broadcast": "192.168.16.255",
            "gateway": "192.168.16.2",
            "interface": "eno16777736",
            "macaddress": "00:0c:29:aa:b6:83",
            "mtu": 1500,
            "netmask": "255.255.255.0",
            "network": "192.168.16.0",
            "type": "ether"
        },
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false
}

 

 來編寫主節點的/etc/redis.conf文件:

bind {{ansible_default_ipv4.address}}

主節點的劇本

 

[root@bogon palybook]# cat p5.yml
- hosts: web
  remote_user: root
  tasks:
   - name: copy
     template: src=/etc/redis.conf dest=/etc/redis.conf
   - name: service redis start
     service: name=redis state=started

 

 

 

ansible-playbook p5.yml

在被控節點上會看到grep bind /etc/redis.conf bind變成本身的主機ip了

bind 192.168.16.138

注意

在傳輸文件的時候src能夠寫相對路徑和絕對路徑

在寫相對路徑的時候,須要跟playbook文件同級建立templates目錄

playbook的文件裏寫

- hosts: web
  tasks:
  - name: yum
    yum: name=redis
  - name: copyfile
    template: src=redis.conf dest=/etc/redis.conf
    tags: copyfile
  - name: start
    service: name=redis state=started
跟playbook文件同級建立templates目錄

 

 

6 Handlers: 在發生改變時執行的操做(相似puppet通知機制)

在Handlers:默認是不執行的,當遇到notify 才執行,當notify 裏面的內容改變了,纔會觸發handlers執行

[root@bogon palybook]# cat p5.yml
- hosts: web
  remote_user: root
  tasks:
   - name: copy
     template: src=/etc/redis.conf dest=/etc/redis.conf
     notify: restart
   - name: service redis start
     service: name=redis state=started
  handlers:
   - name: restart
     service: name=redis state=restarted

 

ansible-playbook   p5.yml

PLAY [web] *********************************************************************************************

TASK [Gathering Facts] *********************************************************************************
ok: [192.168.16.138]
ok: [192.168.16.139]

TASK [copy] ********************************************************************************************
changed: [192.168.16.139]
changed: [192.168.16.138]

TASK [service redis start] *****************************************************************************
ok: [192.168.16.138]
ok: [192.168.16.139]

RUNNING HANDLER [restart] ******************************************************************************
changed: [192.168.16.139]
changed: [192.168.16.138]

PLAY RECAP *********************************************************************************************
192.168.16.138             : ok=4    changed=2    unreachable=0    failed=0    skipped=0    rescued=0 ignored=0
192.168.16.139             : ok=4    changed=2    unreachable=0    failed=0    skipped=0    rescued=0 ignored=0

7 when

條件判斷

- hosts: web
  tasks:
  - name: context
    copy: content="大弦嘈嘈如急雨" dest=/tmp/shi.txt
    when: ansible_distribution_major_version=="7"
  - name: context
    copy: content="小弦切切如私語" dest=/tmp/shi.txt
    when: ansible_distribution_major_version=="6"


- hosts: web
  tasks:
  - name: context
    copy: content="大弦嘈嘈如急雨" dest=/tmp/shi.txt
    when: user=="7"
  - name: context
    copy: content="小弦切切如私語" dest=/tmp/shi.txt
    when: user=="6"
 ansible-playbook -e user=7 p13.yml 

 

8 循環

- hosts: web
  tasks:
  - name: createuser
    user: name={{item}}
    with_items:
    - alex40
    - alex41
    - alex42
    - alex43

 

 

- hosts: web
  tasks:
  - name: createuser
    user: name={{item}}
    with_items:
    - alex50
    - alex51
    - alex52
    - alex53
  - name: creategroup
    group: name={{item}}
    with_items:
    - wusir50
    - wusir51
    - wusir52

 

建立alex60 61 62 63 用戶,組分別是 wusir60 61 62 63

- hosts: web
  tasks:
  - name: creategroup
    group: name={{item}}
    with_items:
    - wusir60
    - wusir61
    - wusir62
    - wusir63
  - name: createuser
    user: name={{item.name}} group={{item.group}}
    with_items:
    - {"name":"alex60","group":"wusir60"}
    - {"name":"alex61","group":"wusir61"}
    - {"name":"alex62","group":"wusir62"}
    - {"name":"alex63","group":"wusir63"}

 




==================================================
php.ini
時區
on66


部署rpm包的lamp環境
- hosts: webserver
remote_user: root
tasks:
- name: install httpd
yum: name=httpd state=present
- name: install mysql-server
yum: name=mysql-server state=present
- name: install php
yum: name=php state=present
- name: httpd conf
copy: src=/home/ansible/file/httpd.conf dest=/etc/httpd/conf/httpd.conf mode=644
- name: mysql conf
copy: src=/home/ansible/file/my.cnf dest=/etc/my.cnf mode=644
- name: php conf
copy: src=/home/ansible/file/php.ini dest=/etc/php.ini mode=644
notify:
- start mysql
- start httpd
- name: service status
shell: netstat -anplt | grep -E '(mysqld|httpd)' > /tmp/lamp.status
- name: get lamp.status
fetch: src=/tmp/lamp.status dest=/tmp/
- name: test page
copy: src=/home/ansible/file/test.html dest=/var/www/html/test.html

handlers:
- name: start mysql
service: name=mysqld state=started
- name: start httpd
service: name=httpd state=started

=============================================

變量使用

經常使用的變量通常就兩種
一種爲用戶本身定義的變量
一種爲facts獲取的變量(即ansible webserver -m setup查到的變量)
#ansible webserver -m setup //獲取webserver信息

 

一自定義變量

1.用戶在.yml文件自定義變量
示例:
[root@master ansible]# vim /home/ansible/1.yml
- hosts: webserver
remote_user: root
vars:
- var1: "abc"
- var2: 123
tasks:
- name: test vars
shell: echo "{{ var1 }} {{ var2 }}" >> /tmp/var.txt

[root@master ansible]# vim /home/ansible/1.yml
- hosts: webserver
remote_user: root
vars:
- packname: "nmap"
tasks:
- name: install package
yum: name={{ packname }} state=present

2.經過-e參數傳遞的變量
[root@master ansible]# ansible-playbook 1.yml -e packname=nmap
- hosts: webserver
remote_user: root
tasks:
- name: install package
yum: name={{ packname }} state=present

3.經過主機或者主機組配置文件傳遞的變量
主機:
[root@master ansible]# cat /etc/ansible/hosts
[webserver]
192.168.10.201 packname=nmap
192.168.10.202 packname=nmap

[root@master ansible]# ansible-playbook 1.yml
[root@master ansible]# cat 1.yml
- hosts: webserver
remote_user: root
tasks:
- name: install package
yum: name={{ packname }} state=present

主機組
[root@master ansible]# cat /etc/ansible/hosts
[webserver]
192.168.10.201
192.168.10.202
[webserver:vars]
packname=nmap

[root@master ansible]# cat 1.yml
- hosts: webserver
remote_user: root
tasks:
- name: install package
yum: name={{ packname }} state=present


二.經過facts獲取的系統的變量

即ansible webserver -m setup查到的變量1.獲取系統變量[root@master ansible]# cat 1.yml - hosts: webserver remote_user: root tasks: - name: hostname ipaddrss shell: echo "{{ ansible_nodename}} {{ ansible_all_ipv4_addresses }}" > /tmp/facts.txt - name: fetch file /tmp/facts fetch: src=/tmp/facts.txt dest=/tmp[root@master ansible]# cat /tmp/192.168.10.202/tmp/facts.txt agent202.puppet.com [u'192.168.10.202']2.本地facts(facts.d)自定義系統變量客戶端定義在管控端建立以下目錄:[root@agent202 ~]# mkdir -p /etc/ansible/facts.d建立文件:[root@agent202 ~]# vim /etc/ansible/facts.d/test.fact[general]test_test1=123test_test2=abc[root@master ansible]# ansible webserver -m setup |grep ansible_local -A 5 //-C 5 上下5行 "ansible_local": { "test": { "general": { "test_test1": "123", "test_test2": "abc" } } }[root@master ansible]# cat 1.yml - hosts: webserver remote_user: root tasks: - name: test shell: echo "{{ ansible_local.test.general.test_test1 }} {{ ansible_local.test.general.test_test2 }}" > /tmp/facts.txt - name: fetch file /tmp/facts fetch: src=/tmp/facts.txt dest=/tmp[root@master ansible]# cat /tmp/192.168.10.202/tmp/facts.txt 123 abc變量註冊:常常在playbook中,存儲某個命令的結果在變量中,以備往後訪問是頗有用的. 這樣使用命令模塊能夠在許多方面除去寫站(site)特異事件,據哥例子 你能夠檢測某一個特定程序是否存在這個 ‘register’ 關鍵詞決定了把結果存儲在哪一個變量中常常在playbook中,存儲某個命令的結果在變量中,以備往後訪問是頗有用的. 這樣使用命令模塊能夠在許多方面除去寫站(site)特異事件,據哥例子 你能夠檢測某一個特定程序是否存在這個 ‘register’ 關鍵詞決定了把結果存儲在哪一個變量中[root@master ansible]# cat 1.yml - hosts: webserver remote_user: root tasks: - name: user root shell: grep ^root /etc/passwd register: pass_contents - name: call pass_contents shell: echo {{ pass_contents.stdout }} > /tmp/call.txt 如想查看那些值能夠引用 [root@master ansible]# cat 1.yml - hosts: webserver remote_user: root tasks: - name: user root shell: grep ^root /etc/passwd register: pass_contents - name: call pass_contents shell: echo {{ pass_contents }} > /tmp/call.txt [root@agent202 ~]# cat /tmp/call.txt {uchanged: True, uend: u2016-11-03 22:31:09.754515, ustdout: uroot:x:0:0:root:/root:/bin/bash, ucmd: ugrep ^root /etc/passwd, ustart: u2016-11-03 22:31:09.750428, udelta: u0:00:00.004087, ustderr: u, urc: 0, stdout_lines: [uroot:x:0:0:root:/root:/bin/bash], uwarnings: []} 劇本中的條件判斷ansible和puppet軟件相同 是能夠支持條件判斷,使用when語句如:[root@master ansible]# cat 1.yml - hosts: webserver remote_user: root tasks: - name: install package nmap yum: name=nmap state=present when: ansible_nodename == "agent202.puppet.com" - name: install package httpd yum: name=nmap state=present when: ansible_nodename == "agent201.puppet.com" 使用註冊變量[root@master ansible]# cat 1.yml - hosts: webserver remote_user: root tasks: - name: package is install shell: rpm -q httpd|awk -F'-' '{print $1}' register: httpd_install - name: test httpd service: name=httpd state=restarted when: httpd_install.stdout == 'httpd'- hosts: webserver remote_user: root tasks: - name: mysql user shell: grep ^mysql /etc/passwd | awk -F':' '{print $1}' register: mysql_install - name: test mysqld service service: name=mysqld state=restarted when: mysql_install.rc == 0劇本中的循環如:添加 abc1-abc3用戶[root@master ansible]# cat 1.yml - hosts: webserver remote_user: root tasks: - name: add new users user: name={{ item }} state=present with_items: - abc1 - abc2 - abc3劇本中的roles你如今已經學過 tasks 和 handlers,那怎樣組織 playbook 纔是最好的方式呢?簡單的回答就是:使用 roles ! Roles 基於一個已知的文件結構,去自動的加載某些 vars_files,tasks 以及 handlers。基於 roles 對內容進行分組,使得咱們能夠容易地與其餘用戶分享 roles 。存放角色的位置:/etc/ansible/roles如roles/ common/ # this hierarchy represents a "role" 這裏的結構表明了一個 "role" tasks/ # main.yml # <-- tasks file can include smaller files if warranted handlers/ # main.yml # <-- handlers file templates/ # <-- files for use with the template resource ntp.conf.j2 # <------- templates end in .j2 files/ # bar.txt # <-- files for use with the copy resource foo.sh # <-- script files for use with the script resource vars/ # main.yml # <-- variables associated with this role defaults/ # main.yml # <-- default lower priority variables for this role meta/ # main.yml # <-- role dependenciesapache/ common/ files/ 存放模塊調用的文件(如:copy 和 script) templates/ 存放模板文件 tasks/ 任務存放的目錄,至少包含一個main.yml的文件,該目錄下也能夠有其餘.yml文件,可是須要在main.yml文件中用include指令將其餘.yml文件包含進來(相似 puppet) handlers/ 存放相關觸發執行器的目錄,至少應該包含一個main.yml的文件,文件中定義了觸發器的任務清單,該目錄下也能夠有其餘.yml文件,可是須要在main.yml文件中用include指令將其餘.yml文件包含進來 vars/  變量存放的目錄,至少應該包含一個main.yml的文件,文件中定義了相關的變量及其值,該目錄下也能夠有其餘.yml文件,可是須要在main.yml文件中用include指令將其餘.yml文件包含進來 defaults/ 默認變量存放的目錄,至少應該包含一個main.yml的文件,文件中定義了此角色使用的默認變量,該目錄下也能夠有其餘.yml文件,可是須要在main.yml文件中用include指令將其餘.yml文件包含進來 meta/ 用於存放此角色元數據,至少應該包含一個main.yml的文件,文件中定義當前角色的特殊設定及其依賴關係, 該目錄下也能夠有其餘.yml文件,可是須要在main.yml文件中用include指令將其餘.yml文件包含進來如何調用定義的角色?- hosts: webserver           remote_user: root           roles:              - apache 建立一個測試roles1.建立角色的目錄結構mkdir -pv /etc/ansible/roles/apache/{files,templates,tasks,handlers,vars,default,meta} 2.定義任務:[root@master ansible]# vim /etc/ansible/roles/apache/tasks/main.yml[root@master tasks]# cat /etc/ansible/roles/apache/tasks/main.yml- name: install apache yum: name=httpd state=present- name: get main configure file template: src=httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf- name: get sub configure file template: src=robin.conf.j2 dest=/etc/httpd/conf.d/robin.conf- name: create robin dir file: path=/srv/robin state=directory- name: get web page template: src=index.html.j2 dest=/var/www/html/index.html notify: - restart apache 3.觸發器任務:[root@master tasks]# cat /etc/ansible/roles/apache/handlers/main.yml- name: start apache service: name=httpd state=present4.準備須要的文件[root@master files]# ls /etc/ansible/roles/apache/templateshttpd.conf.j2 index.html.j2 robin.conf.j2

相關文章
相關標籤/搜索