主頁 > 作業系統 > ansible 筆記

ansible 筆記

2020-09-28 18:03:07 作業系統

Ansible , Saltstack , Puppet 三種自動化運維工具,

最近學了ansible視頻幾節課,全部跟著操作了一遍,操作一遍就能記熟了嗎?

不! 不能! 所以,需要將筆記保存下來,以備后查,

“無主無從架構,開箱即用,用完即走.”

###############  Ansible中文權威指南 http://www.ansible.com.cn/ ########

# 一般實驗環境
# 192.168.52.6

# 192.168.52.7
# 192.168.52.8
# 192.168.52.9

wget https://mirrors.aliyun.com/epel/7/x86_64/Packages/e/epel-release-7-12.noarch.rpm
rpm -Uvh epel-release-7-12.noarch.rpm 

yum info ansible
yum install -y ansible

rpm -ql ansible |less

file /usr/bin/ansible

ansible --version
ansible 2.9.3
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, Apr 11 2018, 07:36:10) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]

# /etc/ansible/ansible.cfg  主組態檔(幾乎不必修改)
# /etc/ansible/hosts        主機串列(管理物件)
# /etc/ansible/roles        角色

# hosts主機清單檔案示例:
[vm]
192.168.52.[7:9]
#cent7[b:d]

[appsvrs]
192.168.52.7
192.168.52.8

[dbsvrs]
192.168.52.9
192.168.52.7

 

上面是基本資訊,下面是一些基本命令

# ssh
ansible all -m ping -k          # all 則操作hosts中所有主機
                                # -u 指定用戶名,無此引數則默認當前用戶
                                # -k 需要密碼認
# 可以使用SSH認證后不必再用 -k
ssh-keygen
ssh-copy-id 192.168.52.7
ssh-copy-id 192.168.52.8
ssh-copy-id 192.168.52.9
ansible all -m ping


ansible-doc -s ping             # 獲取ping 模塊簡要幫助
ansible-doc -F |grep zabbix

ansible all --list              # 列出所有主機
ansible dbsvrs --list           # 列出所有主機

 

常見模塊使用

## ping 模塊
ansible 192.168.* -m ping            # 操作hosts中所有192.168開頭主機
ansible appsvrs:dbsvrs -m ping       # or
ansible 'appsvrs:&dbsvrs' -m ping    # and


## command 模塊
ansible-doc command
ansible all -a 'df -h'
ansible all -a 'ls /opt'

ansible all -a 'removes=/opt/1.txt cat /opt/1.txt'  # 不存在則不執行
ansible dbservers -a 'removes=/data/mariadb ls -l /data' 
ansible all -a 'creates=/opt/1.txt cat /opt/1.txt'  # 存在則不執行
ansible dbservers -a 'creates=/data/mariadb ls -l /data'
ansible all -a 'chdir=/home ls'


## shell 模塊
ansible all -m shell -a 'echo $HOSTNAME'

# 例:關閉selinux
ansible all -a 'ls -l /etc/selinux/'
ansible all -m copy -a 'src=https://www.cnblogs.com/root/config dest=/etc/selinux/config backup=yes'  # 本機檔案到遠程
ansible all -a 'cat /etc/selinux/config'
ansible all -m shell -a 'rm -f /etc/selinux/config.*'  # 洗掉備份
ansible all -m shell -a 'reboot' 
ansible all -m shell -a 'last reboot'
ansible all -a 'getenforce'

ansible all -m shell -a 'useradd mongodb'
ansible all -m shell -a 'passwd mongodb' 


## script 模塊
ansible all -m script -a '/root/h.sh'


## copy 復制當前目錄某檔案到遠程
ansible all -m copy -a 'src=https://www.cnblogs.com/frx9527/p/h.sh dest=/root/ mode=000 owner=mongodb'
ansible all -a 'ls -l /root/' 
ansible all -a 'cat /root/h.sh'

# 直接向遠程目錄寫檔案
ansible all -m copy -a 'content="#!/bin/bash\nntpdate cn.pool.ntp.org" dest=/root/f2.sh mode=644 owner=mongodb'
ansible all -a 'cat /root/f2.sh'


## fetch 抓取遠程檔案
ansible all -m shell -a 'tar Jcf /tmp/log.tar.xz /var/log/*.log'
ansible all -m fetch -a 'src=https://www.cnblogs.com/tmp/log.tar.xz dest=/opt'
yum install -y tree
tree /opt
tar tvf /opt/192.168.52.7/tmp/log.tar.xz


## file 模塊
ansible all -m file -a 'state=directory mkdir /test'        # 創建目錄 
ansible all -m file -a 'name=/test/tmp state=directory'
ansible all -m file -a 'name=/tt/tmp/123 state=directory'

ansible all -m file -a 'path=/test/f3 state=touch'          # 創建空檔案
ansible all -m file -a 'name=/test/f3 state=absent'         # 洗掉檔案
ansible all -m file -a 'name=/tt/ state=absent'             # 洗掉目錄(包括子目錄和檔案)

ansible all -m file -a 'src=https://www.cnblogs.com/etc/passwd dest=/test/pwd.lmk state=link' # 創建軟鏈接
ansible all -a 'ls -l /test'


## hostname 模塊
ansible 192.168.52.7 -m hostname -a 'name=cent7b'


## cron 模塊
ansible all -m cron -a 'minute=* weekday=1,3,5 job="/usr/bin/wall FBI warning" name=warn'  # new
ansible all -m cron -a 'disabled=true job="/usr/bin/wall FBI warning" name=warn'           # disabled
ansible all -m cron -a 'disabled=yes job="/usr/bin/wall FBI warning" name=warn'            # disabled
ansible all -m cron -a 'disabled=Y job="/usr/bin/wall FBI warning" name=warn'              # disabled
ansible all -m cron -a 'disabled=no job="/usr/bin/wall FBI warning" name=warn'             # enabled
ansible all -m cron -a 'disabled=false job="/usr/bin/wall FBI warning" name=warn'          # enabled

ansible all -m cron -a 'state=absent job="/usr/bin/wall FBI warning" name=warn'            # delete


## yum 模塊
ansible all -m yum -a 'name=* state=latest'            # 更新所有包 
ansible all -m yum -a 'name=tree state=latest'         # 安裝
ansible all -m yum -a 'name=tree,vim,ntp state=present'   # 安裝多個包
ansible all -m yum -a 'name=tree state=absent'            # 洗掉
ansible all -m shell -a 'rpm -q tree'

ansible all -m copy -a 'src=https://www.cnblogs.com/root/samba-4.8.3-6.el7_6.x86_64.rpm dest=/root/'  # rpm 安裝
ansible all -m yum -a 'name=/root/samba-4.8.3-6.el7_6.x86_64.rpm disable_gpg_check=Y'
ansible all -m yum -a 'name=lsof update_cache=yes'        # 同時更新快取
ansible all -m yum -a 'name=dstat update_cache=yes'       # dstat 是監控工具


## service 模塊
ansible-doc -s service
ansible all -m service -a 'name=zabbix-server state=stopped'  # reloaded, restarted, started
ansible all -m service -a 'name=mysqld state=restarted'

ansible all -m service -a 'name=zabbix-server enabled=no'
ansible all -a 'systemctl is-enabled zabbix-server'


## user 模塊
ansible appsvrs -m user -a 'name=nginx shell=/sbin/nologin system=yes home=/home/nginx groups=root,bin uid=80 comment="nginx service"'
ansible all -a 'getent passwd nginx'
ansible appsvrs -m user -a 'name=nginx state=absent remove=yes'

ansible appsvrs -m group -a 'name=nginx system=yes gid=80'   # 創建組
ansible appsvrs -m group -a 'name=nginx state=absent'        # 洗掉組
ansible all -a 'getent group nginx'

 

galaxy 類似于腳本庫,可以下載現成的腳本作為參考  控制臺則是ansible的互動界面

## ------------------------------- galaxy ------------------------------
ansible-galaxy install geerlingguy.nginx 
ansible-galaxy list geerlingguy.nginx 
ansible-galaxy list 
cd .ansible/roles/
cp geerlingguy.nginx/ my.nginx -rp             # 創建副本
ansible-galaxy list 

ansible-galaxy remove geerlingguy.nginx/       # 或者直接洗掉 roles/下的目錄

ansible-console                                # 控制臺
# root@appsvrs(2)[f:5]        # 用戶@組(數量)[請求數:5]
    cd 192.168.52.8                            # 切換主機
    user name=test1 state=absent remove=yes    # 洗掉遠程用戶
    

 

YAML 語法 Yet Another Markup Language

#### YAML語法:
# 單一檔案中,連續三個字符(---)區分多個檔案,而三個點(...)則表示檔案結尾
# 次行開始寫playbook內容,一般建議寫功能
# 使用 # 號注釋
# 縮進必須統一,不能空格與Tab混用
# 縮進級別必須一致,程式判定配置的級別是根據縮進和換行來實作
# 嚴格區分大小寫
# k/v 的值可同行也可換行,同行使用冒號分隔(: )
# v 可以是字串,也可以是另一個串列
# 一個完整的代碼塊最少需要包括 name 和 task
# 一個 name 只能包括一個 task 
# YAML 擴展名為 yml 或 yaml

## List 串列,所有元素以 - 開頭
---
# 一個美味水果的串列
- Apple
- Orange
- Strawberry
- Mango

## Dictionary 字典,通常用 k/v 組成
---
# 一位職工的記錄
name: Elly
job: Developer
skill: Elite

 

playbook

## ------------------------------- playbook ----------------------------
# hello.yml
---
- hosts: appsvrs
  remote_user: root

  tasks:
    - name: hello
      command: hostname

ansible-playbook hello.yml  # 執行 hello.yml

# ansible-vault encrypt hello.yml                   # 加密檔案
# ansible-vault decrypt hello.yml                   # 解密檔案
# ansible-vault view hello.yml                      # 查看
# ansible-vault edit hello.yml                      # 編輯
# ansible-vault rekey hello.yml                     # 換密碼
# ansible-vault create h.yml                        # 直接創建加密的檔案
ansible-playbook hello.yml --ask-vault-pass         # 直接運行加密檔案

 

playbook 操作檔案示例

# file.yml
---
- hosts: dbservers
  remote_user: root

  tasks:
    - name: create new file
      file: name=/data/newfile state=touch
    - name: new user
      user: name=test2 system=yes shell=/sbin/nologin
    - name: install tree
      yum: name=tree
    - name: copy config
      copy: src=https://www.cnblogs.com/root/hello.yml dest=/data/
    - name: copy test html
      copy: src=files/test.html dest=/data/
    - name: start service
      service: name=squid state=restarted enabled=yes

ansible-playbook --syntax-check file.yml    # 僅語法檢查
ansible-playbook -C file.yml                # 模擬執行,不產生結果
ansible-playbook file.yml                   # 真正的執行

# src檔案內容更新后,再次執行playbook,會覆寫舊檔案

ansible-playbook file.yml --list-hosts           # 列出主機
ansible-playbook file.yml --list-tasks           # 列出任務
ansible-playbook file.yml --limit 192.168.52.8   # 限制執行
ansible-playbook file3.yml --ask-vault-pass      # 涉及加密檔案


# file3.yml
---
- hosts: dbservers
  remote_user: root
  become: yes                       # 改變用戶
  become_user: mongodb              # 變成誰
  become_method: sudo               # playbook 時需要 -K

  tasks:
    - name: create new file
      file: name=/data/newfile5 state=touch

    - name: cp files
      copy: src=https://www.cnblogs.com/frx9527/p/file.yml dest=/data/
    - name: cp test html
      copy: src=files/test.html dest=/data

ansible-playbook file3.yml -K       # become_user 密碼

 

playbook 中使用Handlers 與 notify ,以及 tags

## Handlers  與 notify 
# act1.yml
---
- hosts: vm
  remote_user: root

  tasks:
    - name: install httpd pkg
      yum: name=httpd
      tags: insthttpd
    - name: copy conf file
      copy: src=https://www.cnblogs.com/frx9527/p/httpd.conf dest=/etc/httpd/conf/ backup=yes
      notify:
      - restart httpd
      - chk httpd process
    
    - name: start service
      service: name=httpd state=started enabled=yes
      tags: starthttpd
 
  handlers:
    - name: restart httpd
      service: name=httpd state=restarted
    - name: chk httpd process
      shell: killall -0 httpd > /tmp/httpd.log      # yum install psmisc

# 執行指定的 tags 步驟
ansible-playbook -t insthttpd,starthttpd act1.yml

# tags可以同名,則相同tags的動作都會被執行
ansible-playbook act2.yml -t httpd

 

playbook 中使用變數

#------------------------- 模塊 setup 用來收集主機的系統資訊
ansible vm -m setup -a 'filter=ansible_hostname'
ansible vm -m setup -a 'filter=ansible_fqdn'
ansible vm -m setup -a 'filter=*ipv4*'


# ------------------------- 變數 ---------------------------------------
# 可以命令列,playbook, role , /etc/ansible/hosts 中定義
## 1. app.yml  # 執行時傳入變數
---
- hosts: vm
  remote_user: root

  tasks:
    - name: install pkg
      yum: name={{ pkname }}
    - name: start service
      service: name={{ pkname }} state=started enabled=yes

ansible-playbook -e 'pkname=vsftpd' app.yml                      # 傳入
ansible-playbook -e 'pkname1=httpd pkname2=memcached' app2.yml   # 多個

# ansible vm -m shell -a 'rpm -q httpd memcached '          
# ansible vm -m yum -a 'name=httpd,memcached state=absent'   


## 2. playbook 中定義并使用變數 app3.yml
---
- hosts: vm
  remote_user: root
  vars:
    - pkname1: httpd
    - pkname2: vsftpd

  tasks:
    - name: install pkg
      yum: name={{ pkname1 }}
    - name: install pkg2
      yum: name={{ pkname2 }}

ansible-playbook app3.yml       # 無需再傳入變數


## 3. hosts檔案中定義變數
[vm]
192.168.52.5   http_port=8181         # 普通變數
192.168.52.6   http_port=8080
192.168.52.7

[vm:vars]                             # 公共變數
nodename=www
domainame=bbc.com
http_port=80


# app4.yml
---
- hosts: vm
  remote_user: root
  
  tasks:
    - name: set hostname
      hostname: name={{nodename}}{{http_port}}.{{domainame}}
   
# 變數優先級指定: 命令列 > 組態檔, 普通 > 公共
ansible-playbook -e 'nodename=web' app4.yml    # 指定變數值
ansible vm -a 'hostname' 

#
4. 使用系統變數 (如 setup 模塊中的) testvars.yml
---
- hosts: vm
  remote_user: root

  tasks:
    - name: create log file
      file: name=/data/{{ ansible_fqdn }}.log state=touch mode=600 owner=nginx

ansible-playbook testvars.yml     # ansible_fqdn 為系統變數

#
5. 使用專門的變數檔案 # vars.yml
var1: httpd
var2: vsftpd

# testvars2.yml
---
- hosts: vm
  remote_user: root
  vars_files:
    - vars.yml
  
  tasks:
    - name: install pkg
      yum: name={{ var1 }}
      
    - name: create files
      file: name=/data/{{ var2 }}.log state=touch

ansible-playbook testvars2.yml    
ansible vm -m shell -a 'rpm -q httpd'
ansible vm -a 'ls /data/'


# ansible 管理容量在300臺左右,再多,性能跟不上
# gather_facts: false

 

模板的使用

#------------------------- Jinja2 template ----------------------------# 
# template 模塊只能用于playbook
ansible-doc template

mkdir template
cp /etc/nginx/nginx.conf template/nginx.conf.j2

ansible vm -m setup |grep cpu     # 得到 ansible_processor_vcpus

# 修改模板檔案 nginx.conf.j2  修改cpu和埠為變數
user nginx;
worker_processes {{ ansible_processor_vcpus // 2 }};
...
        listen       {{ http_port }} default_server;
        listen       [::]:{{http_port }} default_server;
...


# 修改腳本 testemp.yml
---
- hosts: vm
  remote_user: root

  tasks:
    - name: install nginx
      yum : name=nginx
    - name: copy template
      template: src=https://www.cnblogs.com/frx9527/p/nginx.conf.j2 dest=/etc/nginx/nginx.conf
      notify: restart nginx
    - name: start service
      service: name=nginx state=started enabled=yes
      
  handlers:
    - name: restart nginx
      service: name=nginx state=restarted

ansible-playbook testemp.yml        # 運行并驗證
ansible vm -a 'netstat -nltp' 
ansible vm -m shell -a 'ps -aux |grep nginx' 
ansible vm -a 'cat /etc/nginx/nginx.conf'

 

tasks 中使用 when

# 在 tasks 中使用 when ------------------------------------------------
# 參考 https://www.cnblogs.com/nb-blog/p/10565658.html

ansible vm -m setup -a "filter=ansible_distribution"                # CentOS
ansible vm -m setup -a "filter=ansible_distribution_major_version"  # 7

# 再次修改 testemp.yml
---
- hosts: vm
  remote_user: root

  tasks:
    - name: install nginx
      yum : name=nginx
    - name: copy template for centos 7
      template: src=https://www.cnblogs.com/frx9527/p/nginx.conf7.j2 dest=/etc/nginx/nginx.conf
      when: 
        - ansible_distribution == "CentOS"
        - ansible_distribution_major_version == "7"
      notify: restart nginx
    - name: copy template for centos 6
      template: src=https://www.cnblogs.com/frx9527/p/nginx.conf6.j2 dest=/etc/nginx/nginx.conf
      when: ansible_distribution_major_version == "6"
      notify: restart nginx
    - name: start service
      service: name=nginx state=started enabled=yes
      
  handlers:
    - name: restart nginx
      service: name=nginx state=restarted

ansible-playbook testemp.yml     # 執行并驗證  注意 skipping 資訊
ansible vm -a 'cat /etc/nginx/nginx.conf'
ansible vm -m shell -a 'ps -aux |grep nginx' 

 

tasks 中使用 with_items 串列,以及 嵌套子變數

# 迭代 with_items 用法  testitem.yml -----------------------------------
---
- hosts: vm
  remote_user: root

  tasks:
    - name: create some files
      file: name=/data/{{ item }} state=touch
      with_items:
        - f1.txt
        - f2.txt
        - f3.txt
    - name: install some pkg
      yum: 
        name: ['htop', 'sl', 'hping3']


# 使用嵌套子變數 testitem2.yml ----------------------------------------
---
- hosts: vm
  remote_user: root

  tasks:
    - name: create groups
      group: name={{ item }}
      with_items:
        - g1
        - g2
        - g3
    - name: create users
      user: name={{ item.name }} group={{ item.gp }}
      with_items:
        - { name: 'user1', gp: 'g1' }
        - { name: 'user2', gp: 'g2' }
        - { name: 'user3', gp: 'g3' }

ansible
-playbook testitem2.yml # 執行并驗證 ansible vm -a 'cat /etc/group' ansible vm -a 'cat /etc/passwd'

 

使用 for 回圈 , if 條件

### for 回圈   testfor.yml --------------------------------------------
---
- hosts: vm
  remote_user: root
  vars:
    ports:
      - 81
      - 82
      - 83

  tasks:
    - name: copy conf
      template: src=https://www.cnblogs.com/frx9527/p/for1.conf.j2 dest=/data/for1.conf
# templates/for1.conf.j2
{% for p in ports %}
server{
    listen {{ p }}
}
{% endfor %}

ansible-playbook testfor.yml         # 執行并驗證
ansible vm -a 'cat /data/for1.conf'  

### for 回圈 結合變數字典  testfor2.yml -------------------------------
---
- hosts: vm
  remote_user: root
  vars:
    apps:
      - web1:
        port: 81
        name: app1
        dir: /data/web1
      - web2:
        port: 82
        name: app2
        dir: /data/web2
      - web3:
        port: 83
        name: app3
        dir: /data/web3

  tasks:
    - name: copy conf
      template: src=https://www.cnblogs.com/frx9527/p/for2.conf.j2 dest=/data/for2.conf

# templates/for2.conf.j2
{% for p in apps %}
server{
    listen {{ p.port }}
    servername {{ p.name }}
    documentroot {{ p.dir }}
}
{% endfor %}

ansible-playbook testfor2.yml            # 執行并驗證
ansible vm -a 'cat /data/for2.conf'  

## 使用 if 判斷 testif.yml --------------------------------------------
---
- hosts: vm
  remote_user: root
  vars:
    apps:
      - web1:
        port: 81
        #name: app1
        dir: /data/web1
      - web2:
        port: 82
        name: app2
        dir: /data/web2
      - web3:
        port: 83
        #name: app3
        dir: /data/web3

  tasks:
    - name: copy conf
      template: src=https://www.cnblogs.com/frx9527/p/if.conf.j2 dest=/data/if.conf

# if.conf.j2
{% for p in apps %}
server{
    listen {{ p.port }}
    {% if p.name is defined %}
        servername {{ p.name }}
    {% endif %}
    documentroot {{ p.dir }}
}
{% endfor %}

ansible-playbook testif.yml            # 執行并驗證
ansible vm -a 'cat /data/if.conf'  

 

### 插播一些 centos 有趣的命令: ---------------------------------------
cal       # 當前月 cal -3 三個月
sl         # 跑火車 -F -l -a
linux_logo         # -L list
echo 'dog' |boxes -d dog    # yum install boxes
curl http://wttr.in       # 天氣
#---------------------------------- end -------------------------------------------

 

roles

### roles  用于層次性,結構化地組織 playbook  --------------------------
# 能夠根據層次型結構自動裝載變數檔案、tasks以及handlers等, 
# 在playbook中使用include指令,
# 用于復雜場景,代碼復用度高,
# 一般用于基于主機構建服務場景,也可用于構建守護行程場景中,

mkdir roles/{httpd,mysql,memcached,nginx} -pv
# ansible vm -m shell -a 'userdel -r nginx'
cd nginx
mkdir tasks templates

# 以nginx 為例,tree 結構如下:
├── nginx_roles.yml
└── roles
    ├── httpd
    ├── memcached
    ├── mysql
    └── nginx
        ├── tasks
        │   ├── group.yml
        │   ├── main.yml
        │   ├── restart.yml
        │   ├── start.yml
        │   ├── temp.yml
        │   ├── user.yml
        │   └── yum.yml
        └── templates
            └── nginx.conf.j2

# group.yml 
- name: create group
  group: name=nginx gid=80
  
# user.yml
- name: create user
  user: name=nginx uid=80 group=nginx system=yes shell=/sbin/nologin

# yum.yml
- name: install nginx
  yum: name=ngin

# temp.yml
- name: copy conf
  template: src=https://www.cnblogs.com/frx9527/p/nginx.conf.j2 dest=/etc/nginx/nginx.conf
  
# start.yml
- name: start nginx
  service: name=nginx state=started enabled=yes

# main.yml
- include: group.yml
- include: user.yml
- include: yum.yml
- include: temp.yml
- include: start.yml

# nginx_roles.yml
---
- hosts: vm
  remote_user: root
  roles:
    - role: nginx

ansible-playbook nginx_roles.yml   # 執行并驗證
ansible vm -a 'cat /etc/nginx/nginx.conf'  
ansible vm -a 'ps -aux |grep nginx'  


# 以apache為例 --------------------------------------------------
ansible vm -m shell -a 'yum remove -y httpd'
ansible vm -m user -a 'name=apache state=absent remove=yes'

# tree

├── httpd_role.yml
└── roles
    └── httpd
         ├── files
         │   └── httpd.conf
         ├── tasks
         │   ├── cpfile.yml
         │   ├── main.yml
         │   ├── yum.yml
         │   ├── start.yml
         │   └── user.yml
         └── templates

# main.yml
- include: user.yml
- include: yum.yml
- include: cpfile.yml
- include: start.yml

# httpd_role.yml
---
- hosts: vm
  remote_user: root

  roles:
    - httpd

ansible-playbook httpd_role.yml   # 執行并驗證

 

呼叫 多個 role 或跨專案呼叫 role

# some_roles.yml  呼叫多個 role   ----------------------------------
---
- hosts: vm
  remote_user: root
  roles:
    - httpd
    - nginx

# main.yml  跨專案呼叫別的role中任務 
- include: roles/nginx/tasks/temp.yml     

# temp.yml            # 注意檔案內容中使用絕對路徑
- name: copy conf  
  template: src=https://www.cnblogs.com/root/roles/nginx/templates/nginx.conf.j2 dest=/etc/nginx/nginx.conf

# tags  when ---------------------------------------------
---
- hosts: vm
  remote_user: root
  roles:
    - { role: httpd, tags: ['web','httpd'] }
    - { role: nginx, tags: ['web','nginx'], when: ansible_distribution_major_version == "7" }
    - { role: app, tags: "app" }


ansible-playbook -t web some_roles.yml

 

來一個綜合練習 

### 綜合練習 app -------------------------------------------------------
cd /root/roles/app
mkdir tasks templates vars handlers files
# group.yml
- name: create group
  group: name=app system=yes gid=123
  
# user.yml
- name: crt user
  user: name=app system=yes shell=/sbin/nologin uid=123
  
# yum.yml
- name: install pkg
  yum: name=httpd

# template   httpd.conf.j2  包含:
Listen {{ ansible_processor_vcpus * 10 }}
User {{ username }}
Group {{ groupname }}

# vars/main.yml
username: app
groupname: app

# copy.yml
- name: copy conf
  copy: src=https://www.cnblogs.com/frx9527/p/vhost.conf dest=/etc/httpd/conf.d/

# tmpl.yml
- name: copy conf
  template: src=httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
  notify: restart httpd

# start.yml
- name: start httpd
  service: name=httpd state=started enabled=yes

# handlers/main.yml
- name: restart httpd
  service: name=httpd state=restarted

# httpd_role.yml 
---
- hosts: vm
  remote_user: root

  roles:
    - app

# tree
├── httpd_role.yml
├── roles
│   ├── app
│   │   ├── files
│   │   │   └── vhost.conf
│   │   ├── handlers
│   │   │   └── main.yml
│   │   ├── tasks
│   │   │   ├── copy.yml
│   │   │   ├── group.yml
│   │   │   ├── main.yml
│   │   │   ├── start.yml
│   │   │   ├── tmpl.yml
│   │   │   ├── user.yml
│   │   │   └── yum.yml
          ├── templates
          │   └── httpd.conf.j2
          └── vars
              └── main.yml

# 執行并驗證:
ansible-playbook httpd_role.yml
ansible vm -m shell -a 'head /etc/httpd/conf/httpd.conf'
ansible vm -m shell -a 'netstat -nltp'
ansible vm -m shell -a 'ps -aux |grep httpd'

 

練習 :memcached

# memcached 安裝: 根據記憶體大小更改組態檔 ----------------------------
# templates/memcached.j2
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="{{ ansible_memtotal_mb // 4 }}"
OPTIONS=""



# tasks/yum.yml
- name: install memcached
  yum: name=memcached
  
# start.yml
- name: start memcached
  service: name=memcached state=started enabled=yes

# tmpl.yml
- name: copy conf
  template: src=https://www.cnblogs.com/frx9527/p/memcached.j2 dest=/etc/sysconfig/memcached

# main.yml
- include: yum.yml
- include: tmpl.yml
- include: start.yml

# memcached_role.yml
---
- hosts: vm
  remote_user: root
  
  roles:
    - memcached

# 執行并驗證:
ansible-playbook memcached_role.yml
ansible vm -m shell -a 'cat /etc/sysconfig/memcached'

 

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/134807.html

標籤:Linux

上一篇:Virtualbox中ubuntu18配置靜態ip地址及DNS

下一篇:ubuntu 系統 耳機嘶嘶聲 白噪聲 修復

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • CA和證書

    1、在 CentOS7 中使用 gpg 創建 RSA 非對稱密鑰對 gpg --gen-key #Centos上生成公鑰/密鑰對(存放在家目錄.gnupg/) 2、將 CentOS7 匯出的公鑰,拷貝到 CentOS8 中,在 CentOS8 中使用 CentOS7 的公鑰加密一個檔案 gpg -a ......

    uj5u.com 2020-09-10 00:09:53 more
  • Kubernetes K8S之資源控制器Job和CronJob詳解

    Kubernetes的資源控制器Job和CronJob詳解與示例 ......

    uj5u.com 2020-09-10 00:10:45 more
  • VMware下安裝CentOS

    VMware下安裝CentOS 一、軟硬體準備 1 Centos鏡像準備 1.1 CentOS鏡像下載地址 下載地址 1.2 CentOS鏡像下載程序 點擊下載地址進入如下圖的網站,選擇需要下載的版本,這里選擇的是Centos8,點擊如圖所示。 決定選擇Centos8后,選擇想要的鏡像源進行下載,此 ......

    uj5u.com 2020-09-10 00:12:10 more
  • 如何使用Grep命令查找多個字串

    如何使用Grep 命令查找多個字串 大家好,我是良許! 今天向大家介紹一個非常有用的技巧,那就是使用 grep 命令查找多個字串。 簡單介紹一下,grep 命令可以理解為是一個功能強大的命令列工具,可以用它在一個或多個輸入檔案中搜索與正則運算式相匹配的文本,然后再將每個匹配的文本用標準輸出的格式 ......

    uj5u.com 2020-09-10 00:12:28 more
  • git配置http代理

    git配置http代理 經常遇到克隆 github 慢的問題,這里記錄一下幾種配置 git 代理的方法,解決 clone github 過慢。 目錄 git配置代理 git單獨配置github代理 git配置全域代理 配置終端環境變數 git配置代理 主要使用 git config 命令 git單獨 ......

    uj5u.com 2020-09-10 00:12:33 more
  • Linux npm install 裝包時提示Error EACCES permission denied解

    npm install 裝包時提示Error EACCES permission denied解決辦法 ......

    uj5u.com 2020-09-10 00:12:53 more
  • Centos 7下安裝nginx,使用yum install nginx,提示沒有可用的軟體包

    Centos 7下安裝nginx,使用yum install nginx,提示沒有可用的軟體包。 18 (flaskApi) [root@67 flaskDemo]# yum -y install nginx 19 已加載插件:fastestmirror, langpacks 20 Loading ......

    uj5u.com 2020-09-10 00:13:13 more
  • Linux查看服務器暴力破解ssh IP

    在公網的服務器上經常遇到別人爆破你服務器的22埠,用來挖礦或者干其他嘿嘿嘿的事情~ 這種情況下正確的做法是: 修改默認ssh的22埠 使用設定密鑰登錄或者白名單ip登錄 建議服務器密碼為復雜密碼 創建普通用戶登錄服務器(root權限過大) 建立堡壘機,實作統一管理服務器 統計爆破IP [root ......

    uj5u.com 2020-09-10 00:13:17 more
  • CentOS 7系統常見快捷鍵操作方式

    Linux系統中一些常見的快捷方式,可有效提高操作效率,在某些時刻也能避免操作失誤帶來的問題。 ......

    uj5u.com 2020-09-10 00:13:31 more
  • CentOS 7作業系統目錄結構介紹

    作業系統存在著大量的資料檔案資訊,相應檔案資訊會存在于系統相應目錄中,為了更好的管理資料資訊,會將系統進行一些目錄規劃,不同目錄存放不同的資源。 ......

    uj5u.com 2020-09-10 00:13:35 more
最新发布
  • vim的常用命令

    Vim的6種基本模式 1. 普通模式在普通模式中,用的編輯器命令,比如移動游標,洗掉文本等等。這也是Vim啟動后的默認模式。這正好和許多新用戶期待的操作方式相反(大多數編輯器默認模式為插入模式)。 2. 插入模式在這個模式中,大多數按鍵都會向文本緩沖中插入文本。大多數新用戶希望文本編輯器編輯程序中一 ......

    uj5u.com 2023-04-20 08:43:21 more
  • vim的常用命令

    Vim的6種基本模式 1. 普通模式在普通模式中,用的編輯器命令,比如移動游標,洗掉文本等等。這也是Vim啟動后的默認模式。這正好和許多新用戶期待的操作方式相反(大多數編輯器默認模式為插入模式)。 2. 插入模式在這個模式中,大多數按鍵都會向文本緩沖中插入文本。大多數新用戶希望文本編輯器編輯程序中一 ......

    uj5u.com 2023-04-20 08:42:36 more
  • docker學習

    ###Docker概述 真實專案部署環境可能非常復雜,傳統發布專案一個只需要一個jar包,運行環境需要單獨部署。而通過Docker可將jar包和相關環境(如jdk,redis,Hadoop...)等打包到docker鏡像里,將鏡像發布到Docker倉庫,部署時下載發布的鏡像,直接運行發布的鏡像即可。 ......

    uj5u.com 2023-04-19 09:26:53 more
  • 設定Windows主機的瀏覽器為wls2的默認瀏覽器

    這里以Chrome為例。 1. 準備作業 wsl是可以使用Windows主機上安裝的exe程式,出于安全考慮,默認情況下改功能是無法使用。要使用的話,終端需要以管理員權限啟動。 我這里以Windows Terminal為例,介紹如何默認使用管理員權限打開終端,具體操作如下圖所示: 2. 操作 wsl ......

    uj5u.com 2023-04-19 09:25:49 more
  • docker學習

    ###Docker概述 真實專案部署環境可能非常復雜,傳統發布專案一個只需要一個jar包,運行環境需要單獨部署。而通過Docker可將jar包和相關環境(如jdk,redis,Hadoop...)等打包到docker鏡像里,將鏡像發布到Docker倉庫,部署時下載發布的鏡像,直接運行發布的鏡像即可。 ......

    uj5u.com 2023-04-19 09:19:04 more
  • Linux學習筆記

    IP地址和主機名 IP地址 ifconfig可以用來查詢本機的IP地址,如果不能使用,可以通過install net-tools安裝。 Centos系統下ens33表示主網卡;inet后表示IP地址;lo表示本地回環網卡; 127.0.0.1表示代指本機;0.0.0.0可以用于代指本機,同時在放行設 ......

    uj5u.com 2023-04-18 06:52:01 more
  • 解決linux系統的kdump服務無法啟動的問題

    問題:專案麒麟系統服務器的kdump服務無法啟動,沒有相關日志無法定位問題。 1、查看服務狀態是關閉的,重啟系統也無法啟動 systemctl status kdump 2、修改grub引數,修改“crashkernel”為“512M(有的機器數值太大太小都會導致報錯,建議從128M開始試,或者加個 ......

    uj5u.com 2023-04-12 09:59:50 more
  • 解決linux系統的kdump服務無法啟動的問題

    問題:專案麒麟系統服務器的kdump服務無法啟動,沒有相關日志無法定位問題。 1、查看服務狀態是關閉的,重啟系統也無法啟動 systemctl status kdump 2、修改grub引數,修改“crashkernel”為“512M(有的機器數值太大太小都會導致報錯,建議從128M開始試,或者加個 ......

    uj5u.com 2023-04-12 09:59:01 more
  • 你是不是暴露了?

    作者:袁首京 原創文章,轉載時請保留此宣告,并給出原文連接。 如果您是計算機相關從業人員,那么應該經歷不止一次網路安全專項檢查了,你肯定是收到過資訊系統技術檢測報告,要求你加強風險監測,確保你提供的系統服務堅實可靠了。 沒檢測到問題還好,檢測到問題的話,有些處理起來還是挺麻煩的,尤其是線上正在運行的 ......

    uj5u.com 2023-04-05 16:52:56 more
  • 細節拉滿,80 張圖帶你一步一步推演 slab 記憶體池的設計與實作

    1. 前文回顧 在之前的幾篇記憶體管理系列文章中,筆者帶大家從宏觀角度完整地梳理了一遍 Linux 記憶體分配的整個鏈路,本文的主題依然是記憶體分配,這一次我們會從微觀的角度來探秘一下 Linux 內核中用于零散小記憶體塊分配的記憶體池 —— slab 分配器。 在本小節中,筆者還是按照以往的風格先帶大家簡單 ......

    uj5u.com 2023-04-05 16:44:11 more