• ansible 安装使用


    ansible

    ansible源码安装

    yum -y install python-jinja2 PyPAML python-parmiko python-babel python-crypto
    tar -zxf ansible-1.5.4.tar.gz
    cd ansible-1.5.4
    python setup.py build
    python setup.py install
    mkdir /etc/ansible
    cp - examples/* /etc/ansible

    报错:

    error: Setup script exited with error: command 'gcc' failed with exit status 1

    yum install gcc libffi-devel python-devel openssl-devel

    error: Installed distribution setuptools 0.9.8 conflicts with requirement setuptools>=11.3
    [root@k8s1 tmp]# git clone https://github.com/pypa/setuptools.git

    ansible yum安装

    cd /etc/yum.repos.d/
    wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.rep

    yum -y install python-jinja2 PyPAML python-parmiko python-babel python-crypto ansible


    ansible 配置文件的作用
    rpm -ql ansible

    /etc/ansible/ansible.cfg
    /etc/ansible/hosts #配置文件,定义了识别的所有主机
    /etc/ansible/roles
    /usr/bin/ansible
    /usr/bin/ansible-console
    /usr/bin/ansible-doc #文档
    /usr/bin/ansible-galaxy
    /usr/bin/ansible-playbook ###剧本



    ansible配置 /etc/ansible/hosts (连接的主机)

    cat /etc/ansible/hosts

    [webserver]
    192.168.1.104

    [dbserver]
    192.168.1.105


    ansible ssh免密码认证

    ssh-kengen -t rsa

    ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.1.104
    ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.1.105

    ansible 命令使用

    使用 -m ping模块,判断客户机是否在线
    ansible all -m ping


    查看主机时间
    ansible all -m command -a "date"


    查看ansilbe 使用方法
    man ansible


    ansible基本语法

    ansible <host-pattern> [-m module_name] [-a args] [options]

    -m command 默认模块,可以不用写。

    查看docker服务器是否启用

    ansible all -m command -a "systemctl status docker.service"

    ansible 所有模块

    ansible-doc -l 查看ansilbe所有模块

    ansible copy模块使用方法、

    ansible-doc -s copy


    [root@localhost yum.repos.d]# ansible-doc -s copy
    - name: Copies files to remote locations.
    action: copy
    backup # Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.
    content # When used instead of 'src', sets the contents of a file directly to the specified value. This is for simple values, for anything complex or with
    formatting please switch to the template module.
    dest= # Remote absolute path where the file should be copied to. If src is a directory, this must be a directory too.
    directory_mode # When doing a recursive copy set the mode for the directories. If this is not set we will use the system defaults. The mode is only set on directories
    which are newly created, and will not affect those that already existed.
    follow # This flag indicates that filesystem links, if they exist, should be followed.
    force # the default is `yes', which will replace the remote file when contents are different than the source. If `no', the file will only be transferred if the
    destination does not exist.
    group # name of the group that should own the file/directory, as would be fed to `chown'
    mode # mode the file or directory should be. For those used to `/usr/bin/chmod' remember that modes are actually octal numbers (like 0644). Leaving off the
    leading zero will likely have unexpected results. As of version 1.8, the mode may be specified as a symbolic mode (for
    example, `u+rwx' or `u=rw,g=r,o=r').
    owner # name of the user that should own the file/directory, as would be fed to `chown'
    remote_src # If False, it will search for src at originating/master machine, if True it will go to the remote/target machine for the src. Default is False.
    Currently remote_src does not support recursive copying.
    selevel # level part of the SELinux file context. This is the MLS/MCS attribute, sometimes known as the `range'. `_default' feature works as for `seuser'.
    serole # role part of SELinux file context, `_default' feature works as for `seuser'.
    setype # type part of SELinux file context, `_default' feature works as for `seuser'.
    seuser # user part of SELinux file context. Will default to system policy, if applicable. If set to `_default', it will use the `user' portion of the policy if
    available
    src # Local path to a file to copy to the remote server; can be absolute or relative. If path is a directory, it is copied recursively. In this case, if path
    ends with "/", only inside contents of that directory are copied to destination. Otherwise, if it does not end with "/",
    the directory itself with all contents is copied. This behavior is similar to Rsync.
    validate # The validation command to run before copying into place. The path to the file to validate is passed in via '%s' which must be present as in the example
    below. The command is passed securely so shell features like expansion and pipes won't work.


    拷贝命令
    ansible all -m copy -a "src=/etc/yum.repos.d/epel-7.repo dest=/tmp"

    检查拷贝是否成功
    ansible all -m command -a "ls /tmp/"


    ansible 使用cron 模块,定义每3分钟同步以下时间
    [root@localhost yum.repos.d]# ansible-doc -s cron

    1. 放置到/etc/crontab文件下
    ansible all -m cron -a "name='sutom job' cron_file=/etc/crontab user=root minute=*/3 hour=* day=* month=* weekday=* job='/usr/sbin/ntpdate 192.168.1.1' state=present"

    删除添加的crontab(state=absent)

    ansible all -m cron -a "backup=yes user=root cron_file=/etc/crontab minute=*/10 hour=* day=* month=* weekday=* name='test' state=absent job='/usr/sbin/ntpdate 192.168.20.220; /sbin/hwclock -w'"



    2. 第二种方法
    ansible all -m cron -a "name='sutom job' user=root minute=*/3 hour=* day=* month=* weekday=* job='/usr/sbin/ntpdate 192.168.1.1'"

    3. 验证crontab 是否添加
    ansible all -m command -a "crontab -l"


    使用group模块新建mysql组
    ansible all -m group -a "gid=306 system=yes name=mysql"

    使用user模块新建mysql用户
    ansible all -m user -a "group=mysql home=/home/mysql name=mysql createhome=yes"


    通过ansible使用yum模块
    ansible-doc -s yum

    ansible all -m yum -a "state=present name=python-devel"

    通过ansible使用service模块
    ansible all -m service -a "state=started name=docker enabled=yes"


    检查服务器启动状态
    ansible all -m command -c "systemctl list-unit-files docker.service"


    ansible playbooks
    例子:

    [root@localhost ~]# cat test.yaml

    - hosts: all
      remote_user: root
      tasks:
        - name: add user
          user:  name=fengjian shell=/bin/bash state=present home=/home/fengjian
        - name: yum bridge-utils
          yum: name=bridge-utils conf_file=/etc/yum.repos.d/epel-7.repo state=present
        - name: yum httpd
          yum: name=httpd conf_file=/etc/yum.repos.d/epel-7.repo state=present
        - name: service httpd start
          service: name=httpd enabled=yes state=reloaded

    notify 与 handlers对应, notify 定义一个标签, handlers调用标签

    - hosts: all
      remote_user: root
      tasks:
        - name: replace httpd config
          copy:	name=httpd.conf src=/root/httpd.conf dest=/etc/httpd/conf/httpd.conf force=yes
          notify:
    	 - restart httpd
    	
      handlers:
        - name: restart httpd
          service: name=httpd state=restarted
    

    ansible 发版

    - hosts: test
      remote_user: root
      vars:
        warpath: "/root/.jenkins/workspace/172.16.230.168/target/senyint-weixin-0.0.1-SNAPSHOT.war"
        codepath: "/data/code/"
        tomcat: "/data/tomcat/"
      tasks:
        - name: rm  /data/code/
          #file: path={{codepath}} state=absent
          shell: rm -rf /data/code/*
        - name: copy war to IDC_dest
          copy: src={{ warpath }} dest={{ codepath }}
        - name:  kill java
          shell: /data/tomcat/bin/shutdown.sh
        - name: 删除/data/webserver/目录
          shell: rm -rf /data/webserver/*
        - name: uzip war -d /data/webserver/
          shell: /usr/bin/unzip {{codepath}}senyint-weixin-0.0.1-SNAPSHOT.war -d /data/webserver/
        - name: start java
          shell: chdir={{tomcat}}bin/ nohup ./startup.sh &

    查看
    ansible test -m command -a 'ls /etc/yum.repos.d/'

    创建目录
    ansible test -m file -a "path=/usr/local/feng state=directory"

    删除
    ansible test -m file -a 'path=/etc/yum.repos.d/163.repo state=absent'

    copy yum源
    ansible test -m copy -a 'src=/etc/yum.repos.d/ali.repo dest=/etc/yum.repos.d/'

    安装软件
    ansible test -m yum -a 'name=httpd state=latest'

    启动
    ansible test -m service -a 'name=httpd state=started'

    查看进程
    ansible test -m shell -a "ps -ef | grep httpd"

    卸载
    ansible test -m yum -a 'name=httpd state=absent'


    删除yum.repos.d 目录下的repo源
    ansbile test -m shell -a "chdir=/etc/yum.repos.d/ rm -rf *"


    创建用户
    ansible test -m user -a "createhome=yes home=/home/user1 password=123456 name=user1 state=present shell=/bin/shell"

    删除用户连同家目录
    ansible test -m user -a "remove=yes user=feng state=absent"


    同步模块rynchronize
    ansible test -m synchronize -a "src=/etc/yum.repos.d/ dest=/root/rpm_package/ delete=yes"


    playbooks


    - host: test
    user: root
    vars:
    - motd_waring: 'WARNING: Use by acme meployee only'
    task:
    - name: setup a motd
    copy: dest=/etc/mode content="{{motd_waring}}"
    notify: say someting
    hadlers:
    - name: say someting
    command: echo "copy ok"


    Target section
    定义将要执行playbook的远程主机组

    host: 定义远程的主机组
    user:执行该任务组的用户
    remote_user: 与user相同
    sudo: 如果设置成yes,执行该任务组的用户再执行任务的时候。获取root权限
    sudo_user:
    connection: 通过什么方式连接到远程主机,默认ssh
    gather_facts: 除非明确说明不需要再远程主机上执行setup模块,否则默认自动执行,
    如果确定不需要setup模块所传递过来的变量,你可以启用该选项。

    Variable session
    定义playbook 运行时需要使用的变量

    vars 声明

    第一种:
    vars:
    - motd_waring: 'WARNING: Use by acme meployee only'

    第二种:
    1. 定义个文件 variables
    http: nginx
    port: 80

    2. test.yaml 引用 variables 文件
    varsfiles:
    - variables #这是上面定义的文件


    vars_files
    vars_prompt 通过交互的方式,等待输入

    - hsts:all
    vars_prompt:
    - name: http
    prompt: please enter something
    private: yes
    #yes 设置成私有,那么输入的不会再屏幕上显示,
    #no 将在屏幕上打印出来。

    Task section
    定义将要在远程主机上执行的任务列表

    比较常用的模块
    template
    set_fact
    pause
    wait_for
    assemble
    add_host
    group_by
    get_url
    debug
    fail


    template 模块是ansible中最常见的模块之一,它可以让你设计一个框架式的配置文件
    如何把ansible需要的值插入到合适的位置,其中jinja2 模版尤为复杂,其中可以包含条件、循环、宏。

    例子
    tasks:
    - name: copy config file to remote server
    template: src=name.conf.j2 dest=/etc/named.conf


    Handler section
    定义task执行完成以后需要调用的任务

    主机清单 Inventory    /etc/ansible/hosts

    [nginx]
    172.16.230.21
    172.16.230.22
    
    [webserver]
    172.16.230.23
    172.15.230.24

    #连续的
    [solr]
    172.168.230.[25:27]

    说明

    对主机进行分组,并给其指定一个组名,主机可以直接使用ip地址,也可以使用域名,还可以使用数字和字母来指定一系列连续的主机 如:

    test[1:3].abc.com 相当于 test1.abc.com   test2.abc.com  test3.abc.com

    使用ssh 密钥通信,可以不用使用 -k 参数

    使用ping 模块测试:

    #all 代表所有的参数
    [root@rocketmq1 ansible]# ansible all -m ping 172.16.230.23 | SUCCESS => { "changed": false, "ping": "pong" } 172.16.230.21 | SUCCESS => { "changed": false, "ping": "pong" } 172.16.230.22 | SUCCESS => { "changed": false, "ping": "pong" }

    如果多台主机的管理账号各不相同, 可以在inventory文件中,分别进行设置

    [test]
    172.168.230.21   ansible_ssh_root=root
    172.168.230.22   ansible_ssh_root=devuser
    172.168.230.23   ansible_ssh_host=nginx1  ansible_ssh_port=30022

     ansible -i /etc/ansible/hosts test -k -m command -a "ls /tmp"

    简单说明:

    ansible_ssh_user 用于指定管理远程主机的账号

    ansible_ssh_host  用于指定管理的主机

    ansbile_ssh_port 用于指定ssh的端口

    ansible_ssh_private_key_file 指定file文件

    host_key_checking=False 当第一次连接远程主机是, 是否会提示输入yes/no

    主机组之间还可以嵌套, 需要使用关键字children示例:

    [k8s:children]
    k8s_master
    k8s_node
    
    [k8s_master]
    172.168.230.21
    
    [k8s_node]
    172.16.230.22
    172.16.230.23

    [root@rocketmq1 ansible]# ansible -i /etc/ansible/hosts k8s -m command -a "ls /root"

    ansible常用模块

    https://docs.ansible.com/ansible/latest/modules/list_of_all_modules.html

    官方将模块按功能分类为:云模块、命令模块、数据库模块、文件模块、资产模块、消息模块、监控模块、网络模块、通知模块、包管理模块、源码控制模块、系统模块、单元模块、web设施模块、windows模块 

    查看模块

    ansible-doc -l

    查看模块的具体用法

    [root@rocketmq1 ansible]# ansible-doc -s file

    1. setup模块,

    主要用于获取主机信息,在playbooks里经常会用到的一个参数gather_facts就与该模块相关。setup模块下经常使用的一个参数是filter参数,具体使用示例如下:

    ansible -i /etc/ansible/hosts  k8s  -m setup -a 'filter=ansible_*_mb'   //查看主机内存信息
    ansible -i /etc/ansible/hosts  k8s -m setup -a 'filter=ansible_eth[0-2]'   //查看地接口为eth0-2的网卡信息
    ansible all -m setup --tree /tmp/facts   //将所有主机的信息输入到/tmp/facts目录下,每台主机的信息输入到主机名文件中(/etc/ansible/hosts里的主机名)

    2. ping模块

    测试主机是否是通的,用法很简单,不涉及参数:

     ansible k8s -m ping

    3. file模块

    file模块主要用于远程主机上的文件操作,file模块包含如下选项: 

    • force:需要在两种情况下强制创建软链接,一种是源文件不存在但之后会建立的情况下;另一种是目标软链接已存在,需要先取消之前的软链,然后创建新的软链,有两个选项:yes|no 

    • group:定义文件/目录的属组 

    • mode:定义文件/目录的权限

    • owner:定义文件/目录的属主

    • path:必选项,定义文件/目录的路径

    • recurse:递归的设置文件的属性,只对目录有效

    • src:要被链接的源文件的路径,只应用于state=link的情况

    • dest:被链接到的路径,只应用于state=link的情况 

    • state:  

      • directory:如果目录不存在,创建目录

      • file:即使文件不存在,也不会被创建

      • link:创建软链接

      • hard:创建硬链接

      • touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间

      • absent:删除目录、文件或者取消链接文件

    #创建软连接
    ansible k8s -m file -a "src=/etc/fstab dest=/tmp/fstab mode=755 owner=root group=root state=link"
     
    #删除/tmp/fstab 文件
    ansible ks8 -m file -a "path=/tmp/fstab state=absent"
    
    #创建文件
    ansible ks8 -m file -a "path=/tmp/test state=touch"

    #创建目录
    ansible k8s -m file -a "path=/tmp/directory
    mode=755 owner=root group=root state=directory"

    4. copy 模块

    复制文件到远程主机,copy模块包含如下选项:

    • backup:在覆盖之前将原文件备份,备份文件包含时间信息。有两个选项:yes|no 

    • content:用于替代"src",可以直接设定指定文件的值 

    • dest:必选项。要将源文件复制到的远程主机的绝对路径,如果源文件是一个目录,那么该路径也必须是个目录 

    • directory_mode:递归的设定目录的权限,默认为系统默认权限

    • force:如果目标主机包含该文件,但内容不同,如果设置为yes,则强制覆盖,如果为no,则只有当目标主机的目标位置不存在该文件时,才复制。默认为yes

    • others:所有的file模块里的选项都可以在这里使用

    • src:要复制到远程主机的文件在本地的地址,可以是绝对路径,也可以是相对路径。如果路径是一个目录,它将递归复制。在这种情况下,如果路径使用"/"来结尾,则只复制目录里的内容,如果没有使用"/"来结尾,则包含目录在内的整个内容全部复制,类似于rsync。 

    • validate :The validation command to run before copying into place. The path to the file to validate is passed in via '%s' which must be present as in the visudo example below.

    ansible k8s -m copy -a "src=/etc/fstab  dest=/tmp/fstab2 owner=root group=root mode=755"

    # 当使用backup选项是,客户端会出现 /tmp/fstab2.317.2019-01-15@14:19:48~ 的备份,前提是/tmp/fstab 内容发生变化。
    ansible k8s -m copy -a "src=/tmp/fstab dest=/tmp/fstab2 owner=root group=root mode=755 backup=yes"

    5. command 磨块

    • argv: # 允许用户以列表和字符串的形式提供命令。只能提供字符串或列表表单,不能同时提供两者。一个或另一个必须是提供。
    • chdir:         在运行命令之前,切换到指定的目录下。
    • creates:    如果它已经存在,这个步骤将不会运行。
    • free_form: (必需)命令模块使用自由格式的命令运行。没有名为“free form”的参数。请参阅示例!
    • removes:   如果它已经存在,那么将运行该步骤。
    • stdin:        将命令的stdin直接设置为指定值。
    • warn:       如果ansible.cfg中的命令“warnings”处于打开状态,则如果设置为“no”,则不要对此特定行发出警告。
    #加入/tmp/file 文件存在,那么跳过 ls /root/
    ansible k8s -m command -a "creates=/tmp/file ls /root/"

    172.16.230.23 | SUCCESS | rc=0 >> skipped, since /tmp/fengjian exists 172.16.230.21 | SUCCESS | rc=0 >> skipped, since /tmp/fengjian exists 172.16.230.22 | SUCCESS | rc=0 >> skipped, since /tmp/fengjian exists


    # 使用 chdir 跳转到 /tmp目录下
    ansible  k8s  -m command -a "chdir=/tmp/ warn=no tar -zcvf aaa.tar.gz fengjian"

    6. shell 模块

    用法和command 模块相同,支持管道

     ansible  k8s  -m shell  -a "ps -ef | grep crond"

    7. service 模块

    用于管理服务
    该模块包含如下选项: 

      • arguments:给命令行提供一些选项 

      • enabled:是否开机启动 yes|no

      • name:必选项,服务名称 

      • pattern:定义一个模式,如果通过status指令来查看服务的状态时,没有响应,就会通过ps指令在进程中根据该模式进行查找,如果匹配到,则认为该服务依然在运行

      • runlevel:运行级别

      • sleep:如果执行了restarted,在则stop和start之间沉睡几秒钟

      • state:对当前服务执行启动,停止、重启、重新加载等操作(started,stopped,restarted,reloaded)

    # 172.16.230.23 启动nginx,并且设置开机启动
    ansible 172.16.230.23 -m service -a "name=nginx enabled=yes state=started"

    #关闭服务
    ansbile 172.16.230.23 -m service -a "name=nginx state=stopped"

    #查看服务使用 shell 模块管道
    ansible 172.16.230.23 -m shell -a "ps -ef | grep nginx"

    8. cron模块

    用于管理计划任务包含如下选项: 

    • backup:对远程主机上的原任务计划内容修改之前做备份 

    • cron_file:如果指定该选项,则用该文件替换远程主机上的cron.d目录下的用户的任务计划 

    • day:日(1-31,*,*/2,……) 

    • hour:小时(0-23,*,*/2,……)  

    • minute:分钟(0-59,*,*/2,……) 

    • month:月(1-12,*,*/2,……) 

    • weekday:周(0-7,*,……)

    • job:要执行的任务,依赖于state=present 

    • name:该任务的描述 

    • special_time:指定什么时候执行,参数:reboot,yearly,annually,monthly,weekly,daily,hourly 

    • state:确认该任务计划是创建还是删除 

    • user:以哪个用户的身份执行

    # 每5分钟执行一次ntpdate 同步时间
    ansible k8s -m cron -a 'name=ntpdate minute=*/5 job="/usr/bin/ntpdate 192.168.20.220 user=root"'

    [root@rocketmq1 ansible]# crontab -l
    #Ansible: ntpdate
    */5 * * * * /usr/bin/ntpdate 192.168.20.220 user=root

    # 每三分钟 执行ls /home
    ansible k8s -m cron -a "name='每隔3分钟ls /home' minute=*/3 user=root job='ls /home'"

    # 删除 name=ntpdate 的计划任务
    ansible k8s -m cron -a "name=ntpdate state=absent"

     9 yum模块

    使用yum包管理器来管理软件包,其选项有: 

    • config_file:yum的配置文件 

    • disable_gpg_check:关闭gpg_check 

    • disablerepo:不启用某个源 

    • enablerepo:启用某个源

    • name:要进行操作的软件包的名字,也可以传递一个url或者一个本地的rpm包的路径 

    • state:状态(present,absent,latest)

    ansible k8s -m yum -a 'name=httpd state=latest'
    
    ansible k8s -m yum -a 'name="@Development tools" state=present'
    
    ansible k8s -m yum -a 'name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present'
    #删除repo源
    ansible k8s -m file -a "path=/etc/yum.repos.d/CentOS-Sources.repo state=absent"
    
    #拷贝新的repo源
    ansible k8s -m copy  -a "src=/root/epel.repo dest=/etc/yum.repos.d/"
    
    #安装httpd软件
    ansible k8s -m yum -a 'name=httpd state=installed'
    
    启动http软件
    ansible k8s -m service  -a 'name=httpd  state=started'

    user 模块

    • home:指定用户的家目录,需要与createhome配合使用

    • groups:指定用户的属组

    • uid:指定用的uid

    • password:指定用户的密码

    • name:指定用户名

    • createhome:是否创建家目录 yes|no

    • system:是否为系统用户

    • remove:当state=absent时,remove=yes则表示连同家目录一起删除,等价于userdel -r

    • state:是创建还是删除 absent, present,

    • shell:指定用户的shell环境

    
    
    echo "123456" | openssl passwd -1 -salt $(< /dev/urandom tr -dc '[:alnum:]' | head -c 32) -stdin
    $1$4P4PlFuE$ur9ObJiT5iHNrb9QnjaIB0

    创建用户 ansible k8s
    -m user -a "createhome=yes home=/home/user1 password=$1$4P4PlFuE$ur9ObJiT5iHNrb9QnjaIB0 state=present name=user1"
    删除用户
    ansible k8s -m user -a "name=user1 remove=yes state=absent"

    synchronize 模块

    使用rsync同步文件,其参数如下:

    • archive: 归档,相当于同时开启recursive(递归)、links、perms、times、owner、group、-D选项都为yes ,默认该项为开启

    • checksum: 跳过检测sum值,默认关闭

    • compress:是否开启压缩

    • copy_links:复制链接文件,默认为no ,注意后面还有一个links参数

    • delete: 删除不存在的文件,默认no

    • dest:目录路径

    • dest_port:默认目录主机上的端口 ,默认是22,走的ssh协议

    • dirs:传速目录不进行递归,默认为no,即进行目录递归

    • rsync_opts:rsync参数部分

    • set_remote_user:主要用于/etc/ansible/hosts中定义或默认使用的用户与rsync使用的用户不同的情况

    • mode: push或pull 模块,push模的话,一般用于从本机向远程主机上传文件,pull 模式用于从远程主机上取文件

       src=some/relative/path dest=/some/absolute/path rsync_path="sudo rsync"
        src=some/relative/path dest=/some/absolute/path archive=no links=yes
        src=some/relative/path dest=/some/absolute/path checksum=yes times=no
        src=/tmp/helloworld dest=/var/www/helloword rsync_opts=--no-motd,--exclude=.git mode=pull

    playbook 是由一个或者多个play 组成的列表, play的主要功能在于将事先归并为一组的主机装扮成实现通过ansible中的task定义好角色,从根本上来讲,所谓task无非是调用ansible的一个module,将多个play组织在一个palybook中, 即可以让他们联合起来按事先编排的机制完成某一个任务。

    ansible-playbook的简单使用方法: ansible-playbook   xxxx.yml 。

    playbooks组成部分

    target  section 

      定义将要执行palybook的远程主机组

    variable  section

      定义playbook 运行时需要使用的变量

    task section

      定义将要在远程主机上执行的任务列表

    handler section

      定义task执行完成以后需要调用的任务

    hosts:  定义远程的主机组

    user: 执行该任务组的用户

    remote_user:  与user 相同

    sudo: 如果设置为yes,执行该任务组的用户在执行任务的时候,获取root权限。

    sudo_user:  如果设置user 为tom, sudo为yes, sudo_user为jerry,则tom用户会获取jerry用户的权限

    connecton: 通过什么方式连接到远程主机,默认是ssh

    gather_facts: 除非你明确不需要setup模块所传递过来的变量,你可以启动该参数。

    cat  user.yaml

    - hosts: all
      user: root
      gather_facts: false
      vars:
        user: "test"
      tasks:
        - name: create  user
          user: name="`user`"

    variable section

    vars

      vars:
        user: "test"
        mode: "777"


    vars_files

    #新建文件variables, 内容为 port: 80, http: nginx
    cat  variables
    port: 80
    http: nginx

    # files/test1.txt 复制的时候调用 variables中的变量
    cat files/test1.txt
    {{http}}
    {{port}}

    #yaml文件中引用文件

    - hosts: k8s
    user: root
    gather_facts: false
    vars_files:
    - variables #引用文件
    tasks:
    - name: print IP
       template: src=files/test1.txt dest=/tmp/test1.txt

    var_prompt   通过交互的方式输入值

    #####################################################################################################

    ansible 通过ssh 实现配置管理,应用部署,任务执行等功能, 建议配置ansible 端能基于秘钥认证的方式联系各个被管理节点

    ansible <host-pattern> [-m  module_name]  [-a  args]

    --version 显示版本

    -m module  制定模块,默认为command

    -v 详细过程 -vv  -vvv 更详细

    --list-hosts 显示主机清单中的所有主机

    -k, --ask-pass  提示输入ssh连接密码,默认key验证

    -K, --ask-become-pass提示输入sudo口令

    -C, --check检查,并不执行

    -T, --timeout=TIMEOUT执行命令的超时时间,默认10s

    -u, --user=REMOTE_USER执行远程的用户

    -b, --become 代替旧版的sudo 切换。

    command 模块:  对 |  &    $HOSTNAME  <> 特殊的字符,支持有问题, 需要使用shell 模块

    ansible-playbook

    列表做循环
    
    ---
    - hosts: all
      remote_user: root
    
      tasks:
        - name: create some files
          file: name=/data/{{ item }}  state=touch
          when: ansible_distribution_major_version == "7"
          tags: createfiles
          with_items:
            - file1
            - file2
            - file3
        - name:  installpackage 
          yum: name={{ item }} state=present
          when: ansible_distribution_major_version == "7"
          tags: installpackage
          with_items:
            - htop
            - sl
            - hping3

    创建3个组, 把3个用户加入到三个组中

    ---
    - hosts: all
      remote_user: root
    
      tasks:
        - name: create some group
          group: name={{ item }}
          when: ansible_distribution_major_version == "7"
          tags: creategroup
          with_items:
            - g1
            - g2
            - g3
        - name: create some user
          user: name={{ item.user }}  group={{ item.group }}
          when: ansible_distribution_major_version == "7"
          tags: createuser
          with_items:
            - {user: "u1", group: "g1"}
            - {user: "u2", group: "g2"}
            - {user: "u3", group: "g3"}

    playbook 中 template  for  if

    列表方式:

    [root@monitor1 templates]# cat for1.conf.j2 
    {% for  p_port in  ports %}
    server {
        listen  {{ p_port }}
    }
    {% endfor %}
    [root@monitor1 templates]# cat ../templatefor.yaml 
    ---
    - hosts: all
      remote_user: root
      vars:
        ports:
          - 81
          - 82
          - 83
    
      tasks:
        - name: copy template config
          template: src=for1.conf.j2 dest=/data/for1.conf

    字典方式:

    ---
    - hosts: all
      remote_user: root
      vars:
        ports:
          - listen_port: 81
          - listen_port: 82
          - listen_port: 83
    
      tasks:
        - name: copy template config
          template: src=for2.conf.j2 dest=/data/for2.conf

    模板

    [root@monitor1 ansible]# cat templates/for2.conf.j2 
    {% for  p_port in  ports %}
    server {
        listen  {{ p_port.listen_port }}
    }
    {% endfor %}

    在列表中嵌套字典

    [root@monitor1 ansible]# cat   templatefordictlist.yaml 
    ---
    - hosts: all
      remote_user: root
      vars:
        ports:
          - name: master1
            port: 6433
            rootdir: /data/master1/data
          - name: node1
            port: 10255
            rootdir: /data/node1/data
          - name: node2
            port: 10255
            rootdir: /data/node2/data
    
      tasks:
        - name: template copy k8s config
          template: src=for3.conf.j2   dest=/data/for3.conf

    模板:

    [root@monitor1 ansible]# cat templates/for3.conf.j2 
    {% for  p_port in  ports %}
    server {
        listen  {{ p_port.name }}
            servername {{ p_port.port }}
            root {{ p_port.rootdir }}
    }
    {% endfor %}

    if 语句

    {% for  p_port in  ports %}
    server {
        listen  {{ p_port.name }}
            {% if  p_port.servername is defined %}
            servername {{ p_port.port }}
            {% endif %}
            root {{ p_port.rootdir }}
    }
    {% endfor %}
    hostvars允许你访问另一个主机的变量,当然前提是ansible已经收集到这个主机的变量了
    group_names:是当前主机所在的group列表
    groups: 是所有inventory的group列表
    inventory_hostname: 是在inventory里定义的主机名
    play_hosts是当前的playbook范围内的主机列表
    inventory_dir和inventory_file是定义inventory的目录和文件

    内置变量ansible_version

    先从一个简单的内置变量说起,比如,我们可以通过内置变量ansible_version获取到ansible的版本号,示例命令如下

    [root@docker ansible]#  ansible -i hosts test1 -m debug -a "msg={{ansible_version}}"
    172.16.230.51 | SUCCESS => {
        "msg": {
            "full": "2.8.2", 
            "major": 2, 
            "minor": 8, 
            "revision": 2, 
            "string": "2.8.2"
        }
    }

    二、内置变量hostvars

    hostvars可以帮助我们在操作当前主机时获取到其他主机中的信息。

    假设,我想要在操作test70主机时获取到test71主机中的facts信息

    [root@server4 ~]# cat nz.yml 
    ---
    - name: "play 1: Gather facts of test1"
      hosts: test1
      remote_user: root
    
    - name: "play 2: Get facts of testC when operating on test2"
      hosts: test2
      remote_user: root
      tasks:
      - debug:
          msg: "{{hostvars['test1'].ansible_ens32.ipv4}}"

    上例中有两个play,第一个play针对testC主机执行,但是第一个play中没有显式指定任何task(后文会解释原因),第二个play针对testB主机执行,在第二个play中只有一个task,即使用debug模块,输出了testC主机中的eth0网卡的IP信息,如你所见,我们可以借助hostvars在操作当前主机时输出其他主机中的facts信息,上例中使用hostvars加上清单中的主机名称再加上facts的key,即可获取到对应的facts信息,有了前文的总结作为基础,你一定想到了,上例中的msg的值改为如下写法也是可以的。

    摘自:

    https://blog.csdn.net/qq_35887546/article/details/105177305?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase

  • 相关阅读:
    input文本框输入限制(正则表达式)
    SQL Server通用型分页存储过程
    简单易学的数据图表
    HTML中input文本框只读不可编辑的方法
    SQL添加外键约束的方式
    +1 也要睁着眼
    博客园的自定义皮肤
    网站收集整理
    jQuery extend方法介绍
    HTML5本地存储
  • 原文地址:https://www.cnblogs.com/fengjian2016/p/5796209.html
Copyright © 2020-2023  润新知