ansible 第二版

ansible 第二版

Acha
2021-07-16 / 0 评论 / 236 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2021年07月19日,已超过1256天没有更新,若内容或图片失效,请留言反馈。

主机清单

简介

  • 基础知识
    • 格式
    • 主机 & 组
  • 变量
  • 继承
  • 调用

常见格式

ini
[root@ansible project]# cat hosts 
mail.example.com
www[01:50].example.com:
jumper ansible_port=5555 ansible_host=192.0.2.50

[webservers]
foo.example.com
bar.example.com

[dbservers]
one.example.com
two.example.com
three.example.com

[webservers:vars]
http_port: 8080

[servers:children]
webservers
dbservers
yaml
[root@ansible project]# cat hosts 
all:
  hosts:
    foo.example.com
    www[01:50].example.com:
    mysql01:
      ansible_host: 192.168.100.10
      ansible_port: 22
  vars:
    ntp_server: net.atlanta.example.com
    http_port: 8080
  children:
    webservers:
      hosts:
        foo.example.com:
        bar.example.com:
    dbservers:
      hosts:
        one.example.com:
        two.example.com:
        three.example.com:

主机清单文件 (inventory)

# 主机 + 密码 + 端口
ansible_host=192.168.100.10 ansible_port=2222 ansible_user=root ansible_password=123456

# 别名 + 主机
jumper ansible_host=192.0.2.50

# 主机 + 组(密钥)
[webservers]
192.168.100.12
192.168.100.13

ad-hoc

Ansible ad-hoc 在一个或多个受管节点上自动执行单个任务

格式

ansible <pattern> -m <module_name> -a "<module_name>""
< pattern > 主机 模块名 模块选项

体验

ping 模块

[root@ansible ansible]# ansible youto -m ping -i hosts
10.35.172.74 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
[root@ansible ansible]# ansible youto -i hosts --list-host  
  hosts (1):
    10.35.172.74

playbook

yum

选项 解释 参数
name 软件名 httpd、httpd-2.4、url
state 状态 latest、present、absent
exclude 排除 kernel*
enablerepo 仓库 centos
  • Examples

    # 安装最新的 httpd
    - name: install the latest version of Apache
      yum:
        name: httpd
        state: latest
    
    # 
    - name: ensure a list of packages installed
      yum:
        name: "{{ packages }}"
      vars:
        packages:
        - httpd
        - httpd-tools
    
    - name: remove the Apache package
      yum:
        name: httpd
        state: absent
    
    - name: install the latest version of Apache from the testing repo
      yum:
        name: httpd
        enablerepo: testing
        state: present
    
    - name: install one specific version of Apache
      yum:
        name: httpd-2.2.29-1.4.amzn1
        state: present
    
    - name: upgrade all packages
      yum:
        name: '*'
        state: latest
    
    - name: upgrade all packages, excluding kernel & foo related packages
      yum:
        name: '*'
        state: latest
        exclude: kernel*,foo*
    
    - name: install the nginx rpm from a remote repo
      yum:
        name: http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm
        state: present
    
    - name: install nginx rpm from a local file
      yum:
        name: /usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm
        state: present
    
    - name: install the 'Development tools' package group
      yum:
        name: "@Development tools"
        state: present
    
    - name: install the 'Gnome desktop' environment group
      yum:
        name: "@^gnome-desktop-environment"
        state: present
    
    - name: List ansible packages and register result to print with debug later.
      yum:
        list: ansible
      register: result
    
    - name: Install package with multiple repos enabled
      yum:
        name: sos
        enablerepo: "epel,ol7_latest"
    
    - name: Install package with multiple repos disabled
      yum:
        name: sos
        disablerepo: "epel,ol7_latest"
    
    - name: Install a list of packages
      yum:
        name:
          - nginx
          - postgresql
          - postgresql-server
        state: present
    
    - name: Download the nginx package but do not install it
      yum:
        name:
          - nginx
        state: latest
        download_only: true

copy

选项 解释 参数
src 源路径 /root/http.conf.j2
dest 目标路径 /etc/httpd/conf/httpd.conf
owner 属主 root
group 属组 root
mode 权限 644
backup 备份 yes
content 写内容 hi,boy
  • Examples

    - name: Copy file with owner and permissions
      copy:
        src: /srv/myfiles/foo.conf
        dest: /etc/foo.conf
        owner: foo
        group: foo
        mode: '0644'
    
    - name: Copy file with owner and permission, using symbolic representation
      copy:
        src: /srv/myfiles/foo.conf
        dest: /etc/foo.conf
        owner: foo
        group: foo
        mode: u=rw,g=r,o=r
    
    - name: Another symbolic mode example, adding some permissions and removing others
      copy:
        src: /srv/myfiles/foo.conf
        dest: /etc/foo.conf
        owner: foo
        group: foo
        mode: u+rw,g-wx,o-rwx
    
    - name: Copy a new "ntp.conf file into place, backing up the original if it differs from the copied version
      copy:
        src: /mine/ntp.conf
        dest: /etc/ntp.conf
        owner: root
        group: root
        mode: '0644'
        backup: yes
    
    - name: Copy a new "sudoers" file into place, after passing validation with visudo
      copy:
        src: /mine/sudoers
        dest: /etc/sudoers
        validate: /usr/sbin/visudo -csf %s
    
    - name: Copy a "sudoers" file on the remote machine for editing
      copy:
        src: /etc/sudoers
        dest: /etc/sudoers.edit
        remote_src: yes
        validate: /usr/sbin/visudo -csf %s
    
    - name: Copy using inline content
      copy:
        content: '# This file was moved to /etc/other.conf'
        dest: /etc/mine.conf
    
    - name: If follow=yes, /path/to/file will be overwritten by contents of foo.conf
      copy:
        src: /etc/foo.conf
        dest: /path/to/link  # link to /path/to/file
        follow: yes
    
    - name: If follow=no, /path/to/link will become a file and be overwritten by contents of foo.conf
      copy:
        src: /etc/foo.conf
        dest: /path/to/link  # link to /path/to/file
        follow: no

get_url

选项 解释 参数
url URL地址
dest 目标路径
checksum MD5校验
  • Examples

    - name: Download foo.conf
      get_url:
        url: http://example.com/path/file.conf
        dest: /etc/foo.conf
        mode: '0440'
    
    - name: Download file and force basic auth
      get_url:
        url: http://example.com/path/file.conf
        dest: /etc/foo.conf
        force_basic_auth: yes
    
    - name: Download file with custom HTTP headers
      get_url:
        url: http://example.com/path/file.conf
        dest: /etc/foo.conf
        headers:
          key1: one
          key2: two
    
    - name: Download file with check (sha256)
      get_url:
        url: http://example.com/path/file.conf
        dest: /etc/foo.conf
        checksum: sha256:b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c
    
    - name: Download file with check (md5)
      get_url:
        url: http://example.com/path/file.conf
        dest: /etc/foo.conf
        checksum: md5:66dffb5228a211e61d6d7ef4a86f5758
    
    - name: Download file with checksum url (sha256)
      get_url:
        url: http://example.com/path/file.conf
        dest: /etc/foo.conf
        checksum: sha256:http://example.com/path/sha256sum.txt
    
    - name: Download file from a file path
      get_url:
        url: file:///tmp/afile.txt
        dest: /tmp/afilecopy.txt
    
    - name: < Fetch file that requires authentication.
            username/password only available since 2.8, in older versions you need to use url_username/url_password
      get_url:
        url: http://example.com/path/file.conf
        dest: /etc/foo.conf
        username: bar
        password: '{{ mysecret }}'

file

选项 解释 参数
path 目标路径 /opt/centos
state 状态 touch、directory
owner 属主 root
group 属组 root
mode 权限 755
recurse 递归 yes
  • Examples

    - name: Change file ownership, group and permissions
      file:
        path: /etc/foo.conf
        owner: foo
        group: foo
        mode: '0644'
    
    - name: Give insecure permissions to an existing file
      file:
        path: /work
        owner: root
        group: root
        mode: '1777'
    
    - name: Create a symbolic link
      file:
        src: /file/to/link/to
        dest: /path/to/symlink
        owner: foo
        group: foo
        state: link
    
    - name: Create two hard links
      file:
        src: '/tmp/{{ item.src }}'
        dest: '{{ item.dest }}'
        state: hard
      loop:
        - { src: x, dest: y }
        - { src: z, dest: k }
    
    - name: Touch a file, using symbolic modes to set the permissions (equivalent to 0644)
      file:
        path: /etc/foo.conf
        state: touch
        mode: u=rw,g=r,o=r
    
    - name: Touch the same file, but add/remove some permissions
      file:
        path: /etc/foo.conf
        state: touch
        mode: u+rw,g-wx,o-rwx
    
    - name: Touch again the same file, but dont change times this makes the task idempotent
      file:
        path: /etc/foo.conf
        state: touch
        mode: u+rw,g-wx,o-rwx
        modification_time: preserve
        access_time: preserve
    
    - name: Create a directory if it does not exist
      file:
        path: /etc/some_directory
        state: directory
        mode: '0755'
    
    - name: Update modification and access time of given file
      file:
        path: /etc/some_file
        state: file
        modification_time: now
        access_time: now
    
    - name: Set access time based on seconds from epoch value
      file:
        path: /etc/another_file
        state: file
        access_time: '{{ "%Y%m%d%H%M.%S" | strftime(stat_var.stat.atime) }}'
    
    - name: Recursively change ownership of a directory
      file:
        path: /etc/foo
        state: directory
        recurse: yes
        owner: foo
        group: foo
    
    - name: Remove file (delete file)
      file:
        path: /etc/foo.txt
        state: absent
    
    - name: Recursively remove directory
      file:
        path: /etc/foo
        state: absent

service

选项 解释 参数
name 服务名 httpd
state 状态 started、
enabled 开机自启 yes/no
  • Examples

    - name: Start service httpd, if not started
      service:
        name: httpd
        state: started
    
    - name: Stop service httpd, if started
      service:
        name: httpd
        state: stopped
    
    - name: Restart service httpd, in all cases
      service:
        name: httpd
        state: restarted
    
    - name: Reload service httpd, in all cases
      service:
        name: httpd
        state: reloaded
    
    - name: Enable service httpd, and not touch the state
      service:
        name: httpd
        enabled: yes
    
    - name: Start service foo, based on running process /usr/bin/foo
      service:
        name: foo
        pattern: /usr/bin/foo
        state: started
    
    - name: Restart network service for interface eth0
      service:
        name: network
        state: restarted
        args: eth0

group

选项 解释 参数
name 组名 youto
gid GID 1234
state 状态 present、absent
system 系统组 yes/no
  • Examples
    - name: Ensure group "somegroup" exists
      group:
        name: somegroup
        state: present

user

选项 解释 参数
name 用户名 acha
uid UID 0527
group 用户组 root
shell 解释器 /bin/bash、/sbin/nologin
state 状态 present、absent
create_home 创建家目录 yes/no
remove 移除家目录 yes/no
generate_ssh_key 创建密钥 yes/no
ssh_key_bits 长度 2048
ssh_key_file 密钥位置 .ssh/id_rsa
  • Examples

    - name: Add the user 'johnd' with a specific uid and a primary group of 'admin'
      user:
        name: johnd
        comment: John Doe
        uid: 1040
        group: admin
    
    - name: Add the user 'james' with a bash shell, appending the group 'admins' and 'developers' to the user's groups
      user:
        name: james
        shell: /bin/bash
        groups: admins,developers
        append: yes
    
    - name: Remove the user 'johnd'
      user:
        name: johnd
        state: absent
        remove: yes
    
    - name: Create a 2048-bit SSH key for user jsmith in ~jsmith/.ssh/id_rsa
      user:
        name: jsmith
        generate_ssh_key: yes
        ssh_key_bits: 2048
        ssh_key_file: .ssh/id_rsa
    
    - name: Added a consultant whose account you want to expire
      user:
        name: james18
        shell: /bin/zsh
        groups: developers
        expires: 1422403387
    
    - name: Starting at Ansible 2.6, modify user, remove expiry time
      user:
        name: james18
        expires: -1

cron

选项 解释 参数
  • Examples

    - name: Ensure a job that runs at 2 and 5 exists. Creates an entry like "0 5,2 * * ls -alh > /dev/null"
      cron:
        name: "check dirs"
        minute: "0"
        hour: "5,2"
        job: "ls -alh > /dev/null"
    
    - name: 'Ensure an old job is no longer present. Removes any job that is prefixed by "#Ansible: an old job" from the crontab'
      cron:
        name: "an old job"
        state: absent
    
    - name: Creates an entry like "@reboot /some/job.sh"
      cron:
        name: "a job for reboot"
        special_time: reboot
        job: "/some/job.sh"
    
    - name: Creates an entry like "PATH=/opt/bin" on top of crontab
      cron:
        name: PATH
        env: yes
        job: /opt/bin
    
    - name: Creates an entry like "APP_HOME=/srv/app" and insert it after PATH declaration
      cron:
        name: APP_HOME
        env: yes
        job: /srv/app
        insertafter: PATH
    
    - name: Creates a cron file under /etc/cron.d
      cron:
        name: yum autoupdate
        weekday: "2"
        minute: "0"
        hour: "12"
        user: root
        job: "YUMINTERACTIVE=0 /usr/sbin/yum-autoupdate"
        cron_file: ansible_yum-autoupdate
    
    - name: Removes a cron file from under /etc/cron.d
      cron:
        name: "yum autoupdate"
        cron_file: ansible_yum-autoupdate
        state: absent
    
    - name: Removes "APP_HOME" environment variable from crontab
      cron:
        name: APP_HOME
        env: yes
        state: absent

mount

选项 解释 参数
src 源路径 10.35.200.189:/data
path 目标路径 /opt
fstype 磁盘类型 nfs
opts defaults
state 状态 present、unmounted、mounted、absent
  • Examples

    # Before 2.3, option 'name' was used instead of 'path'
    - name: Mount DVD read-only
      mount:
        path: /mnt/dvd
        src: /dev/sr0
        fstype: iso9660
        opts: ro,noauto
        state: present
    
    - name: Mount up device by label
      mount:
        path: /srv/disk
        src: LABEL=SOME_LABEL
        fstype: ext4
        state: present
    
    - name: Mount up device by UUID
      mount:
        path: /home
        src: UUID=b3e48f45-f933-4c8e-a700-22a159ec9077
        fstype: xfs
        opts: noatime
        state: present
    
    - name: Unmount a mounted volume
      mount:
        path: /tmp/mnt-pnt
        state: unmounted
    
    - name: Mount and bind a volume
      mount:
        path: /system/new_volume/boot
        src: /boot
        opts: bind
        state: mounted
        fstype: none

selinux

选项 解释 参数
state 状态 enforcing、permissive、disabled
  • Examples

    - name: Enable SELinux
      selinux:
        policy: targeted
        state: enforcing
    
    - name: Put SELinux in permissive mode, logging actions that would be blocked.
      selinux:
        policy: targeted
        state: permissive
    
    - name: Disable SELinux
      selinux:
        state: disabled

firewalld

选项 解释 参数
service 服务名 httpd
port 端口号 8080-9090
permanent 永久放行 yes
immediate 临时放行 yes
state 状态 enabled
zone 区域 public
  • Examples

    - firewalld:
        service: https
        permanent: yes
        state: enabled
    
    - firewalld:
        port: 8081/tcp
        permanent: yes
        state: disabled
    
    - firewalld:
        port: 161-162/udp
        permanent: yes
        state: enabled
    
    - firewalld:
        zone: dmz
        service: http
        permanent: yes
        state: enabled
    
    - firewalld:
        rich_rule: rule service name="ftp" audit limit value="1/m" accept
        permanent: yes
        state: enabled
    
    - firewalld:
        source: 192.0.2.0/24
        zone: internal
        state: enabled
    
    - firewalld:
        zone: trusted
        interface: eth2
        permanent: yes
        state: enabled
    
    - firewalld:
        masquerade: yes
        state: enabled
        permanent: yes
        zone: dmz
    
    - firewalld:
        zone: custom
        state: present
        permanent: yes
    
    - firewalld:
        zone: drop
        state: present
        permanent: yes
        icmp_block_inversion: yes
    
    - firewalld:
        zone: drop
        state: present
        permanent: yes
        icmp_block: echo-request
    
    - name: Redirect port 443 to 8443 with Rich Rule
      firewalld:
        rich_rule: rule family=ipv4 forward-port port=443 protocol=tcp to-port=8443
        zone: public
        permanent: yes
        immediate: yes
        state: enabled

ansible 变量

如何定义变量?

  • play
  • vars

定义变量

vars:
  - v1: value
  - v2: value
  - v3: value

使用变量

{{ v1 }}

实例

1、在playbook文件中的play使用变量
- hosts: oldboy
  vars:
    - web_packages: httpd-2.4.6
    - ftp_packages: vsftpd-3.0.2

  tasks:
    - name: Installed {{ web_packages }} {{ ftp_packages }}
      yum: 
        name:
          - "{{ web_packages }}"
          - "{{ ftp_packages }}"
        state: present  
2、通过定义一个变量文件,然后使用playbook进行调用
[root@m01 project1]# cat vars_public.yml 
web_packages: httpd-2.4.6
ftp_packages: vsftpd-3.0.2

[root@m01 project1]# cat vars_1.yml
- hosts: oldboy
  vars_files: ./vars_public.yml

  tasks:
    - name: Installed {{ web_packages }} {{ ftp_packages }}
      yum: 
        name:
          - "{{ web_packages }}"
          - "{{ ftp_packages }}"
        state: present
3、通过inventory主机清单进行变量定义
## 在项目目录下创建两个变量的目录,host_vars group_vars
#--------------------- group_vars ---------------- 
#1)在当前的项目目录中创建两个变量的目录
[root@ansible project1]# mkdir host_vars
[root@ansible project1]# mkdir group_vars

#2)在group_vars目录中创建一个文件,文件名与inventory清单中的组名称要保持完全一致。
[root@ansible project1]# cat group_vars/oldboy
web_packages: wget
ftp_packages: tree

#3)编写playbook,只需在playbook文件中使用变量即可。
[root@ansible project1]# cat f4.yml 
- hosts: oldboy
  tasks:
    - name: Install Rpm Packages "{{ web_packages }}" "{{ ftp_packages }}"
      yum: 
        name: 
          - "{{ web_packages }}"
          - "{{ ftp_packages }}"
        state: present

group_vars目录中文件名与hosts清单中的组名保持一致

系统提供了一个特殊组 all,在group_vars目录下建立一个all文件,所有组都可使用

#--------------------- hosts_vars ----------------        
#1)在host_vars目录中创建一个文件,文件名与inventory清单中的主机名称要保持完全一致
[root@ansible project1]# cat hosts 
[oldboy]
172.16.1.7
172.16.1.8

#2)在host_vars目录中创建文件,给172.16.1.7主机定义变量
[root@ansible project1]# cat host_vars/172.16.1.7 
web_packages: zlib-static
ftp_packages: zmap

#3)准备一个playbook文件调用host主机变量
[root@ansible project1]# cat f4.yml 
- hosts: 172.16.1.7
  tasks:
    - name: Install Rpm Packages "{{ web_packages }}" "{{ ftp_packages }}"
      yum: 
        name: 
          - "{{ web_packages }}"
          - "{{ ftp_packages }}"
        state: present

- hosts: 172.16.1.8
  tasks:
    - name: Install Rpm Packages "{{ web_packages }}" "{{ ftp_packages }}"
      yum: 
        name: 
          - "{{ web_packages }}"
          - "{{ ftp_packages }}"
        state: present
4、通过执行playbook时使用-e参数指定变量
[root@m01 project1]# cat vars_7.yml 
- hosts: "{{ hosts }}"  #注意:这是一个变量名称
  tasks:
    - name: Install Rpm Packages "{{ web_packages }}" "{{ ftp_packages }}"
      yum: 
        name: 
          - "{{ web_packages }}"
          - "{{ ftp_packages }}"
        state: present
[root@m01 project1]# #ansible-playbook -i hosts  vars_7.yml -e "hosts=oldboy"

变量优先级

1. 外置传参
2. playbook(vars_files-->vars)
3. inventory(host_vars-->group_vars/group_name-->group_vars-all)

变量注册

register debug


[root@m01 project1]# cat vars_9.yml 
- hosts: oldboy

  tasks:
    - name: Installed Httpd Server
      yum: name=httpd state=present

    - name: Service Httpd Server
      service: name=httpd state=started

    - name: Check Httpd Server
      shell: ps aux|grep httpd
      register: check_httpd

    - name: OutPut Variables
      debug:
        msg: "{{ check_httpd.stdout_lines }}"

facts变量

用来采集被控端的状态指标,比如: IP地址 、主机名称 、cpu信息、内存 等等

采集被控端的信息,赋值到facts变量

查看 face变量

# 将变量保存到 文本里
ansible 172.16.1.8 -m setup -i hosts > face.txt
# 查询备控端内存大小
ansible 172.16.1.8 -m setup -a "filter=ansible_memtotal_mb" -i hosts

memcache

- hosts: oldboy
  tasks:
    - name: Installed Memcached Server
      yum: name=memcached state=present

    - name: Configure Memcached Server
      template: src=./memcached.j2 dest=/etc/sysconfig/memcached

    - name: Service Memcached Server
      service: name=memcached state=started enabled=yes

    - name: Check Memcached Server
      shell: ps aux|grep memcached
      register: check_mem

    - name: Debug Memcached Variables
      debug:
        msg: "{{ check_mem.stdout_lines }}"

task 控制

概述

1. 判断语句  when
   根据主机名称来安装不同的yum仓库
   根据主机的系统安装不同的软件包

2. 循环语句 with_items: 列表     item
   基本循环
   字典循环   facts

3. handlers触发
   notify   通知
   handlers 执行

4. include
   include              tasks
   include_tasks            tasks
   import_playbook          playbook

5. tags标签
   调试模式使用
    -t 指定
    --skip-tags: 跳过

6. 忽略错误ignore_errors: yes

7. 错误处理
   fource_handlers: yes  强制调用handlers(少)
   change_when: false    抑制changed状态
   change_when: (check_nginx.stdout.find('ok')

实例

1、条件判断 when

根据不同操作系统,安装相同的软件包
- hosts: oldboy
  tasks:

    - name: Installed {{ ansible_distribution }} Httpd Server
      yum: name=httpd state=present
      when: ( ansible_distribution == "CentOS" )

    - name: Installed {{ ansible_distribution }} Httpd2 Server
      yum: name=httpd2 state=present
      when: ( ansible_distribution == "Ubuntu" )
为所有的web主机名添加nginx仓库,其余的都跳过添加
- hosts: all
  tasks:
    - name: Create YUM Repo
      yum_repository:
        name: ansible_nginx
        description: ansible_test
        baseurl: https://mirrors.oldboy.com
        gpgcheck: no
        enabled: no
      when: ( ansible_fqdn is match ("web*"))
根据命令执行的结果进行判断
- hosts: all
  tasks:
        #检查httpd服务是否是活动的
    - name: Check Httpd Server
      command: systemctl is-active httpd
      ignore_errors: yes
      register: check_httpd

      #如果check_httpd变量中的rc结果等于0,则执行重启httpd,否则跳过
    - name: Httpd Restart 
      service: name=httpd state=restarted
      when: check_httpd.rc == 0

2、循环语句 with_items

使用循环启动多个服务
- hosts: webserver
  tasks:
    - name: Service Nginx Server
      service: name={{ item }} state=restarted
      with_items:
        - nginx
        - php-fpm
定义变量方式循环安装软件包
- hosts: web
  tasks:
    - name: Installed Httpd Mariadb Package
      yum: name={{ pack }} state=latest
      vars:
       pack:
         - httpd
         - mariadb-server

- hosts: webserver
  tasks:
    - name: Installed Httpd Mariadb Package
      yum: name={{ pack }} state=latest
      vars:
       pack:
         - httpd
         - mariadb-server
使用变量字典循环方式批量创建用户
[root@m01 project1]# cat tasks_6.yml 
- hosts: webserver
  tasks:
     - name: Create User 
       user: name={{ item.name }} groups={{ item.groups }} state=present
       with_items:
         - { name: 'www', groups: 'bin'}
         - { name: 'test', groups: 'root'}

3、handlers 触发器

httpd 更改配置重启服务
- hosts: webserver
  #1.定义变量,在配置文件中调用
  vars:
    http_port: 8881
  #2.安装httpd服务
  tasks:
    - name: Install Httpd Server
      yum: name=httpd state=present
    #3.使用template模板,引用上面vars定义的变量至配置文件中
    - name: Configure Httpd Server
      template: src=./httpd.conf dest=/etc/httpd/conf/httpd.conf
      notify:   #调用名称为Restart Httpd Server的handlers(可以写多个)
        - Restart Httpd Server
    #4.启动Httpd服务
    - name: Start Httpd Server
      service: name=httpd state=started enabled=yes
  #5.如果配置文件发生变化会调用该handlers下面的对应名称的task
  handlers:
    - name: Restart Httpd Server
      service: name=httpd state=restarted

handlers注意事项

  1. handlers仅会在所有tasks结束后运行一次
  2. 只有task发生改变了才会通知handlers触发
  3. handlers是一个特殊的tasks

4、tags标签

打标签

  1. 对一个tasks指定一个tags标签
  2. 对一个tasks指定多个tags标签
  3. 多个tasks任务指定一个tags标签
指定执行某个tags标签
ansible-playbook -i hosts nginx_php.yml -t "test_user"
忽略执行某个tags标签
ansible-playbook -i hosts nginx_php.yml --skip-tags "test_user"

示例

- hosts: webserver
  tasks:
    - name: Install Nfs Server
      yum: name=nfs-utils state=present
      tags: install_nfs

    - name: Service Nfs Server
      service: name=nfs-server state=started enabled=yes
      tags: start_nfs-server

5、include包含

1)编写restart_httpd.yml文件
[root@ansible project1]# cat restart_httpd.yml  
# 注意这是一个tasks所有没有play的任何信息
- name: Restart Httpd Server
  service: name=httpd state=restarted

2)A Project的playbook如下
[root@ansible project1]# cat a_project.yml 
- hosts: webserver
  tasks:
    - name: A Project command
      command: echo "A"

    - name: Restart httpd
      include: restart_httpd.yml

3)B Project的playbook如下
[root@ansible project1]# cat b_project.yml 
- hosts: webserver
  tasks:
    - name: B Project command
      command: echo "B"

    - name: Restart httpd
      include_tasks: restart_httpd.yml



导入一个完整的playbook文件   (play task)
[root@m01 project1]# cat tasks_total.yml 
- import_playbook: ./tasks_1.yml
- import_playbook: ./tasks_2.yml

6、错误忽略ignore_errors

ignore_errors: yes

- hosts: webserver
  tasks:
     - name: Command 
       command: /bin/false
       ignore_errors: yes

     - name: Create File 
       file: path=/tmp/tttt state=touch

7、错误处理changed_when

强制调用handlers
- hosts: webserver
  # 强制调用handlers
  force_handlers: yes 

  tasks:
    - name: Touch File
      file: path=/tmp/bgx_handlers state=touch
      notify: Restart Httpd Server

    - name: Installed Packages
      yum: name=sb state=latest

  handlers:
    - name: Restart Httpd Server
      service: name=httpd state=restarted
关闭changed的状态
- hosts: webserver
  tasks:
    - name: Installed Httpd Server
      yum: name=httpd state=present

    - name: Service Httpd Server
      service: name=httpd state=started

    - name: Check Httpd Server
      shell: ps aux|grep httpd
      register: check_httpd
      changed_when: false

    - name: OutPut Variables
      debug:
        msg: "{{ check_httpd.stdout_lines }}"
使用hanged_when检查tasks任务返回的结果
- hosts: webserver
  tasks: 

    - name: Installed Nginx Server
      yum: name=nginx state=present

    - name: Configure Nginx Server
      copy: src=./nginx.conf.j2 dest=/etc/nginx/nginx.conf
      notify: Restart Nginx Server

    - name: Check Nginx Configure Status
      command: /usr/sbin/nginx -t
      register: check_nginx
      changed_when: 
       - ( check_nginx.stdout.find('successful'))
       - false

    - name: Service Nginx Server
      service: name=nginx state=started 

  handlers:
    - name: Restart Nginx Server
      service: name=nginx state=restarted

lnmp

- hosts: webserver
  tasks:

    - name: Installed Nginx PHP-FPM Server
      yum: name={{ packages }} state=present
      vars:
        packages:
          - nginx
          - php
          - php-fpm
          - php-cli
          - php-pdo
          - php-mbstring
          - php-gd

    - name: Create Nginx Group {{ web_user }}
      group: name={{ web_user }} gid=666 state=present

    - name: Create Nginx User {{ web_user }}
      user: name={{ web_user }} uid=666 group={{ web_user }} state=present

    - name: Create Kod {{ kod_server_path }} Directory
      file: path={{ kod_server_path }} state=directory

    - name: Unzip Kod {{ kod_server_path }} Directory
      unarchive: src=./playbook/kodexplorer4.40.zip dest={{ kod_server_path  }}

    - name: Chown Kod Data {{ web_user }}
      file: path={{ kod_server_path }} owner={{ web_user }} group={{ web_user }} recurse=yes mode=0777

    - name: Configure Nginx Server
      template: src={{ item.src }} dest={{ item.dest }} backup=yes
      with_items:
        - {src: './nginx.conf.j2',dest: '/etc/nginx/nginx.conf'}
        - {src: './kod.conf.j2',dest: '/etc/nginx/conf.d/kod.conf'}
      notify: Restart Nginx Server

    - name: Check Nginx Server
      shell: /usr/sbin/nginx -t
      register: check_nginx
      changed_when: 
        - ( check_nginx.stdout.find('successful'))
        - false

    - name: Configure PHP-FPM Server
      template: src={{ item.src }} dest={{ item.dest }} backup=yes
      with_items:
        - {src: './php.ini.j2',dest: '/etc/php.ini'}
        - {src: './php_www.conf.j2',dest: '/etc/php-fpm.d/www.conf'}
      notify: Restart PHP-FPM Server

    - name: Check PHP-FPM Server
      shell: /usr/sbin/php-fpm -t
      register: check_phpfpm
      changed_when: 
        - ( check_phpfpm.stdout.find('successful'))
        - false

    - name: Start Nginx PHP Server
      service: name={{ item }} state=started enabled=yes
      with_items:
        - nginx
        - php-fpm

  handlers:
    - name: Restart Nginx Server
      service: name=nginx state=restarted

    - name: Restart PHP-FPM Server
      service: name=php-fpm state=restarted


[root@m01 project1]# cat group_vars/all 
#nginx php variables
web_user: www
nginx_conf: /etc/nginx/nginx.conf
nginx_virt: /etc/nginx/conf.d
nginx_code: /ansible_code
server_port: 80
kod_server_name: kod.oldboy.com
kod_server_path: /nginx_code

###
php_fpm_conf: /etc/php-fpm.d/www.conf
php_ini_conf: /etc/php.ini
php_ini_max_upload: 200M

jinja2

{% if EXPR %}...{% elif EXPR %}...{% endif%} 作为条件判断

{% for i in EXPR %}...{% endfor%} 作为循环表达式

{# COMMENT #} 表示注释

jinja实现keepalived
[root@m01 project1]# cat keepalived.conf.j2 
global_defs {     
    router_id {{ ansible_fqdn }}
}

vrrp_instance VI_1 {
{% if ansible_fqdn == "lb01" %}
    state MASTER
    priority 150

{% elif ansible_fqdn == "lb02" %}
    state BACKUP
    priority 100
{% endif %}
###------------------相同点
    interface eth0
    virtual_router_id 50
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
}
    virtual_ipaddress {
        10.0.0.3
    }
}

roles

Roles基于一个已知的文件结构 tasks handlers templates .....

Roles小技巧:

  1. 创建roles目录结构,手动或使用ansible-galaxy init test roles
  2. 编写roles的功能,也就是tasks
  3. 最后playbook引用roles编写好的tasks
[root@m01 project2]# mkdir memcached/{tasks,handlers,templates,vars,files} -pv
mkdir: 已创建目录 "memcached"
mkdir: 已创建目录 "memcached/tasks"
mkdir: 已创建目录 "memcached/handlers"
mkdir: 已创建目录 "memcached/templates"
mkdir: 已创建目录 "memcached/vars"
mkdir: 已创建目录 "memcached/files"
[root@m01 project2]# mkdir {nginx,php-fpm}/{tasks,handlers,templates} -p

galaxy

注:笔记整理自徐亮伟老师的笔记与视频

2

评论

博主关闭了当前页面的评论