设为首页 收藏本站
查看: 889|回复: 0

[经验分享] ansible 文档

[复制链接]

尚未签到

发表于 2018-7-30 10:27:25 | 显示全部楼层 |阅读模式
  Ansiable
  Ansiable的核心组件
  Ansible core
  Host inventory
  Core modules
  Custom modules
  Playbooks(yaml.jinjia2)
  Connect plugin
  Ansible特性
  基于 python 语言实现,由paramike,pyyaml和jinjia2三个关键模块组成
  部署简单,agentless
  默认使用ssh协议
  主从模式,
  Master:ansble.ssh client
  Slave:ssh server
  支持自定义模块,支持各种编程语言
  支持playbook
  基于“模块”完成各种“任务”
  查看ansible版本
  yum list *ansible*
  Available Packages
  ansible-inventory-grapher.noarch                1.0.1-2.el6                epel
  ansible-lint.noarch                             2.0.1-1.el6                epe
  使用的是2.0.1-1版本
  查看ansible 的yum介绍
  s um info ansible
  Loaded plugins: fastestmirror
  Loading mirror speeds from cached hostfile
  * base: mirrors.btte.net
  * epel: mirrors.opencas.cn
  * extras: mirrors.btte.net
  * updates: mirrors.btte.net
  Available Packages
  Name        : ansible
  Arch        : noarch
  Version     : 1.9.4
  Release     : 1.el6
  Size        : 1.7 M
  Repo        : epel
  Summary     : SSH-based configuration management, deployment, and task execution
  : system
  URL         : http://ansible.com
  License     : GPLv3+
  Description :
  : Ansible is a radically simple model-driven configuration
  : management, multi-node deployment, and remote task execution
  : system. Ansible works over SSH and does not require any software
  : or daemons to be installed on remote nodes. Extension modules can
  : be written in any language and are transferred to managed machines
  : automatically.
  基于ssh管理
  1)        基于秘钥认证方式
  2)        在inventory文件中指定账户和密码
  Ansible应用
  安装
  依赖于epel源
  配置文件:/etc/ansible/ansible.cfg
  Invertory:/etc/ansible/hosts
  Cd /etc/ansible
  生成秘钥文件
  ssh-keygen -t rsa
  Generating public/private rsa key pair.
  Enter file in which to save the key (/root/.ssh/id_rsa): liu
  Enter passphrase (empty for no passphrase):
  Enter same passphrase again:

  Your>  Your public key has been saved in liu.pub.
  The key fingerprint is:
  88:13:fd:2d:c9:f5:04:53:f5:55:47:84:d3:b1:a3:0b root@VM_168_49_centos
  The key's randomart image is:
  +--[ RSA 2048]----+
  |          o....*O|
  |     .     o  o.=|
  |    . .   . .  +.|
  |     o + + o  . .|
  |    o . S .E..   |
  |     .   .  . .  |
  |             .   |
  |                 |
  |                 |
  拷贝秘钥文件到远程主机上
  ssh-copy-id -i /root/.ssh/liu.pub root@192.168.203.138
  查看ansible各种模块
  Ansible-doc –l
  Ansible-doc –s MODULE_NAME
  Ansible命令应用基础
  语法 ansible <host-pattern> [-f forks] [-m module_name] [-a args]
  -f forks: 启动的并发线程数
  -m module_name: 要使用的模块
  -a args: 模块特有的参数
  常见模块
  Command: 命令模块,默认模块,用于在远程执行命令
  Ansible all –a ‘date’
  Corn: 任务计划模块,
  State:
  Present: 安装
  Absent:移除
  */10 * * * *
  Ansible websrvs –m cron –a ‘minute=”*/10” job=”/bin/echo hellow” name=”test cron job” state=presentjob” state=present’
  User:用户模块
  ansible websers -m user -a 'user=mysql1 uid=306 system=yes group=mysql1'
  group:组模块
  ansible websers -m group -a 'name=mysql1 gid=306 system=yes'
  copy:
  src:定义本地源文件
  dest:定义目标文件必须是绝对路径
  content:取代src= 二者不能同时使用 表示直接用此处指定的信息生产为目标文件内容
  ansible websers -m copy -a 'src=/etc/fstab dest=/tmp/fstab mode=700 owner=root'
  ansible all –m copy –a ‘content=”hell\nHI mageedu” dest=/tmp/test.ansible’
  file 模块
  path:指定文件路径,可以使用name或dest来代替
  创建文件符号链接
  Src=:指定源文件
  Path=:指明符号链接文件路径
  ansible all –m file –a ‘owner=mysql group=mysql mode=644 path=/tmp/fastab.ansible’
  ansible 192.168.203.133 -m file -a 'owner=puppet group=puppet mode=644 path=/tmp/fstab.link src=/tmp/fstab state=link' 设置链接文件
  测试远程主机的联通性
  ping
  Ansible all –m ping
  Service模块
  Service 指定运行状态
  Enabled: 是否开启自动启动,取值为true 或false
  Name: 服务名称
  State=:状态,取值有started stoped restarted
  Shell模块
  如果使用复杂的命令使用shell模块
  ansible all -m shell -a 'echo asdffa|passwd --stdin user1'
  script:将本地脚本复制到远程主机并运行
  使用相对路径指明脚本
  nsible all -m script -a '/root/block.sh'
  yum 模块
  安装程序包
  Ansible all –m yum –a ‘name=ssh’
  Name=:指明要安装的程序包,可以带上版本号
  State=:present,latest表示安装,absent表示卸载
  Setup
  收集每一个远程主机的facts
  Yaml 介绍
  Yaml 是一个可读性高的表达资料序列格式。
  Yaml特点
  可读性好
  和脚本语言的交互性好
  使用实现语言的数据类型
  有一个一致的信息模型
  易于实现
  可以基于流处理
  表达能力强,扩展好
  Yaml语法
  Yaml的语法和其他高阶语言类似,并且可以简单表达清单,散列表,标量等数据结构。其结构(structure)通过空格来表示,序列(sequence)里的选项用“-“来表示。Map里的键值对用”:“分隔,下面是一个实例
  Name: John smith
  Ago: 41
  Gender: Male
  Spouse:
  Name: Jane Smith
  Age: 37
  Gender: female
  Children
  -        Name: Jimmy Smith
  Age: 17
  Gender: Male
  -        Name: Jenny Smith
  Age: 13
  Gender: female
  同一个数据有多个类叫序列
  List
  列表的所有元素均使用“-“打头
  #A list of tasty fruits
  -        Apple
  -        Orange
  -        Strawberry
  -        Mango
  Dictionary
  字典通过key于valuef 进行标示,例如
  #An employee record
  Name: tom
  Job: it
  Skill: Elite
  也可以将key:value放置于{}中进行表示,例如。
  #An employee recard
  {name: tom, job: it, skill: elite}
  Ansible中使用的Yaml 基础元素
  变量:变量名仅能由字母,数字和下滑下组成但是只能以字母开头
  Inventory
  迭代
  条件测试
  Playbook的组成结构
  inventory
  Modules
  Ad hoc commands
  Playbooks
  Tasks: 任务:即调用模块完成的某操作
  Variables:变量
  Templates:模版
  Handlers:处理器,有某件事满足时触发的事件
  Roles:角色
  Inventory 文件格式
  Inventory文件遵循Ini文件风格,中括号中的字符为组名,可以将同一个主机同时归并到多个不同的组中,此外,当如若目标主机使用了非默认的ssh端口,还可以在主机名称之后使用冒号家端口号来标明。
  Ntp.magedu.com
  [websersers]
  www1.magedu.com:2222
  www2.magedu.com
  [dbservers]
  Db1.magedu.com
  Db2.magedu.com
  Db3.magedu.com
  如果主机名称遵循相似命名模式,还可以使用列表的方式进行标示
  [webservers]
  www[01:50].example.com
  [datebases]
  Db-[a:f].example.com
  主机变量
  可以在inventory中定义主机是为其添加主机变量以便于在playbook中使用,例如:
  [webservers]
  www1.magedu.com http_port=80 maxRequestsPerChild=808
  www2.magedu.com http_port=8080 maxRequestsPerChild=8080
  组变量
  组变量指赋予组内所有主机上的playbook中可以用的变量
  [webservers]
  www1.magedu.com
  www2.magedu.com
  [webservers:vars]
  Ntp_server=ntp.magedu.com
  Nfs_server=nfs.magedu.com
  组嵌套
  Inventory中,组还可以包含其他组。并且也可以向组中的主机指定变量,不过,这些变量只能在ansible-playbook中使用
  [apache]
  http1.magedu.com
  http2.magedu.com
  [nginx]
  Ngx1.magedu.com
  Ngx2.magedu.com
  [webservers:children]
  Apache
  Nginx
  [webservers:vars]
  Ntp_server=ntp.magedu.com
  Ansible playbooks
  Playbook是由一个或多个”play” 组成的列表,play的主要功能在于将事先归并为一组的主机装扮成事先通过ansible中的task定义好的角色。从根本上来讲,所谓task无非是调用ansible的一个module,将多个play组成在一个playbook中,即可以让他们连同起来按事先编排好的机制同唱一台大戏,例如
  -        hosts: webnodes
  Vars:
  http_port: 80
  max_clients: 256
  remote_user: root
  tasks:
  -        name: ensure apache is at the latest version
  Yum: name=httpd state=latest
  -        name: ensure apache is running
  Service: name=httpd state=started
  Handlers
  -        Name: restart apache
  Service: name=httpd state=restarted
  Playbook基础组件
  Hosts和users
  Playbook中的美一个play的目的都是为了让某个或某些主机以某个指定的用户身份执行任务,hosts用于指定要执行指定任务的主机,其中可以是一个或多个由冒号分隔的主机组:remote_user则用于指定远程主机上执行任务的用户,例如
  -        Hosts: webnodes
  Remote_user: root
  不过,remote_users也可以用于各task中,也可以通过指定其通过sudo的方式在远程主机上执行任务,其可用于play全局或某任务:此外,甚至可以在sudo时使用sudu_user指定sudo时切换的用户
  -        Hosts:webnodes
  Remote_user: magedu
  Task:
  -        Name: test connection
  Ping:
  Remote_user: magedu
  Sudo: yes
  任务列表和action
  Play的主体部分是task list,task list中的各任务按次序逐个在hosts中指定的所有主机上执行,即在所有主机上完成第一个任务后在开始第二个,在运行自上而下某个playbook时,如果中途发生错误,所有已执行任务都将可能回滚,因此,在更正playbook后重新执行一次即可。
  Task的目的是使用指定的参数执行模块,而在模块参数中可以使用变量,模块执行时幂等的,这意味着多次执行时安全的,因为其结果均一致。
  每个task都应该有其name,用于playbook的执行结果输出,建议其内容尽可能清晰地描述任务步骤,如果为提供name,,则action的结果将用于输出,
  定义task的可以使用”action: modele options”或”module: options”的格式,推荐使用后者实现向后兼容,如果action一行的内容过多,也使用在行首使用几个空白字符进行换行。
  Tasks:
  -        Name: make sure apache is running
  Service: name=httpd state=running
  在众多模块中,只有command和shell模块仅需要给定一个列表而无需使用“key=value”格式,例如
  Tasks:
  -        Name: disable selinux
  Command: /sbin/setenforce 0
  如果命令或脚本的退出码不为零,可以使用如下方式替代,
  Tasks:
  -        Name: run this command an ignore the result
  Shell: /usr/bin/somecommand || /bin/true
  或者使用ignore_errors来忽略错误信息:
  Tasks:
  -        Name: run this command and ignore the result
  Shell: /usr/bin/somecommand
  Ignore_errors: True
  严格按照格式写要不不能运行
  实例
  基本结构
  -        Host: websers
  Remote_user:
  Tasks:
  -        Task1
  Modulename: module_args
  -        Task2
  Handlers
  用于当关注资源,并当资源出现变化时执行
  - hosts: websers
  remote_user: root
  tasks:
  - name: install httpd package
  yum: name=httpd state=latest
  - name: install configurtion file for httpd
  copy: src=/root/httpd.conf dest=/etc/httpd/conf/httpd.conf
  notify:
  - restart httpd
  - name: start httpd service
  service: enabled=true name=httpd state=started
  handlers:
  - name: restart httpd
  service: name=httpd state=restarted
  变量:
  - hosts: websers
  remote_user: root
  vars:
  - package: httpd
  - service: httpd
  tasks:
  - name: install httpd package
  yum: name=` package ` state=latest
  - name: install configurtion file for httpd
  copy: src=/root/httpd.conf dest=/etc/httpd/conf/httpd.conf
  notify:
  - restart httpd
  - name: start httpd service
  service: enabled=true name=` service ` state=started
  handlers:
  - name: restart httpd
  service: name=httpd state=restarted
  自带的变量引用
  - hosts: websers
  remote_user: root
  tasks:
  - name: copy file
  copy: content="` ansible_all_ipv4_addresses `" dest=/tmp/vars.ansible
  使用主机变量
  vim /etc/ansible/hosts
  [websers]
  192.168.203.135 testvar="100.7"
  [dbsers]
  192.168.203.133
  Vim test.yml
  - hosts: websers
  remote_user: root
  tasks:
  - name: copy file
  copy: content="` ansible_all_ipv4_addresses `, ` testvar `" dest=/tmp/vars.ans
  条件测试
  When:用于条件测试
  - hosts: all
  remote_user: root
  vars:
  - username: user10
  tasks:
  - name: create ` username ` user
  user: name=` username`
  when: ansible_fqdn == "new"
  只有  when: ansible_fqdn == "new" 时上面的才执行
  迭代
  当有需要重复执行的任务时,可以使用迭代机制,其使用格式为将需要迭代的内容定义为item变量引用,并通过with_items语句来指明迭代的元素列表即可
  例如
  -        Name: add serveral users
  User: name=` item ` state=present groups=wheel
  With_items:
  -        Testuser1
  -        Testuser2
  Item为固定变量名
  事实上,with_items中可以使用元素还可以为hashs,例如
  - name: add serveral users
  user: name=` item`.`name ` state=present groups=` item`.`groups `
  with_items:
  - { name: 'testuser1', groups: 'wheel' }
  - { name: 'testuser2', groups: 'whee2' }
  注意: with_items 中的列表值也可以是字典,但引用时要使用item.key
  -        Apache
  -        Php
  -        Mysql.server
  -        { name: apache, conf: conffiles/httpd.conf }
  -        { name: php, conf: conffiles/php.ini }
  -        { name: mysql.server, conf: conffiles/my.cnf }
  Templates模板
  首先服务端更改httpd.conf 为httpd.conf.j2
  Vim httpd.conf.j2
  Listen {{  httpd_port }}
  MaxClents ` maxClents `
  ServerName ` ansible_fqdn `
  [root@web9 ~]# cat /etc/ansible/hosts
  [websers]
  192.168.203.135 httpport=8010 maxClients=100
  [dbsers]
  192.168.203.133 httpport=8080 maxClients=200
  You have new mail in /var/spool/mail/root
  [root@web9 ~]# vim apache.yml
  - hosts: websers
  remote_user: root
  vars:
  - package: httpd
  - service: httpd
  tasks:
  - name: install httpd package
  yum: name=` package ` state=latest
  - name: install configurtion file for httpd
  template: src=/root/templates/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
  notify:
  - restart httpd
  - name: start httpd service
  service: enabled=true name=` service ` state=started
  handlers:
  - name: restart httpd
  service: name=httpd state=restarted
  算数运输
  {{ 3 – 2 }}
  {{ 3/2 }}
  等等
  Tags标签
  在playbook中可以为某个或某些任务定义一个标签,在执行此playbook时,通过为ansible-playbook命令使用—tags选项能实现仅运行指定的tasks而非所有的:
  - hosts: websers
  remote_user: root
  vars:
  - package: httpd
  - service: httpd
  tasks:
  - name: install httpd package
  yum: name=` package ` state=latest
  - name: install configurtion file for httpd
  template: src=/root/templates/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
  tags:
  - conf
  notify:
  - restart httpd
  - name: start httpd service
  service: enabled=true name=` service ` state=started
  handlers:
  - name: restart httpd
  service: name=httpd state=restarted
  命令ansible-playbook apache.yml --tags="conf"
  仅运行conf的命令
  特殊tags: always
  Roles
  Ansible自1.2版本引入的新特性,用于层次性,结构化的组织playbook,roles能够根据层次型结构自动装载变量文件,tasks以及handlers等,要使用roles只需要在playbook中使用include指令即可,简单来说,roles就是通过分别将变量,文件,任务,模块及处理器放置于单独的目录中,并可以便捷的include他们的一种机制,较色一般用于基于主机构建服务的场景中,但也可以是用于构建守护进程等场景中
  Roles:
  1)        目录名同角色名
  2)        目录结构有固定格式
  Files:静态文件
  Templates: jinjia2模板文件
  Tasks: 至少有main.yml文件,定义各tasks:
  Handlers: 至少有一个main.yml文件,定义各handlers
  Vars: 至少有一个main.yml文件,定义变量 并且变量为字典
  Meta: 定义依赖关系等信息
  3)
  Site.yml 定义playbooks,额外也可以有其他yml
  Roles过程实例
  首先建立目录
  mkdir -pv ansilbe_playbooks/roles/{websers,dbsers}/{tasks,files,templates,meta,handlers,vars}
  cd ansible_playbooks
  cd roles/websers
  cp /root/httpd.conf files/
  vim tasks/main.yml
  - name: install httpd package
  yum: name=httpd
  - name: install configuration file
  copy: src=httpd.conf dest=/etc/httpd/conf/httpd.conf
  tags:
  - conf
  notify:
  - restart httpd
  - name: start httpd
  service: name=httpd state=started
  vim handlers/main.yml
  - name: restart httpd
  service: name=httpd state=restarted
  ~
  cd ansilbe_playbooks/
  vim site.yml
  - hosts: websers
  remote_user: root
  roles:
  - websers
  - hosts: dbsers
  remote_user: root
  roles:
  - dbsers
  - hosts: 192.168.203.139
  remote_user: root
  roles:
  - websers
  - dbsers
  Ansible-playbooks site.yml
  有个别的图片没有上传 太麻烦了 会有一两个断点的地方

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-543454-1-1.html 上篇帖子: ansible的条件判断、迭代执行、tags 下篇帖子: ansible playbook(3.7-4.4)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表