1.Ansible Inventory##

(1)静态主机文件

默认的ansible invetory是/etc/hosts文件,可以通过ANSIBLE_HOSTS环境变量或者通过运行命令的时候加上-i

  1. vim /tmp/hosts
  2. # 定义组
  3. [webservers]
  4. 10.187.11.34
  5. 10.187.137.191
  6. # 组变量
  7. [webservers:vars]
  8. ansible_ssh_pass = '123456'

多个静态文件,可以写不同的文件里,文件名字hosts不是必须

inventory可以指向一个目录,这样目录里面所有的文件都会被加载进来,可以通过--list-hosts()来验证

  1. [admin@host-10-187-196-225 hosts_file]$ ansible -i /tmp/hosts_file/ webservers --list-hosts
  2. 10.187.109.116
  3. 10.189.92.46

(2)动态主机文件

ansible.cfg配置文件中的inventory配置项指向一个脚本

这个脚本有一定规范和参数要求

1.支持--list或者-l,这个参数运行后会显示所有的主机以及主机组的信息(JSON格式)

2.支持--host或者-H,这个参数后面需要指定一个host,运行结果会返回这台主机的所有信息(包括认证信息,主机变量等),也是json格式

  1. #!/usr/bin/env python
  2. # -*- coding=utf-8 -*-
  3. #########################
  4. import argparse
  5. import sys
  6. import json
  7. def lists():
  8. r = dict()
  9. h = ['172.17.42.10' + str(i) for i in range(1,4)]
  10. hosts = {'hosts':h}
  11. r['docker'] = hosts
  12. return json.dumps(r,indent=4)
  13. def hosts(name):
  14. r = {'ansible_ssh_pass':'123456'}
  15. cpis = dict(r.items())
  16. return json.dumps(cpis,indent=4)
  17. if __name__ == "__main__":
  18. '''添加argparse的参数类实例,添加一些-l和-H的帮助显示提示'''
  19. parser = argparse.ArgumentParser()
  20. parser.add_argument('-l','--list',help='hosts list',action='store_true')
  21. parser.add_argument('-H','--host',help='hosts vars')
  22. '''vars方法把parser.parse_args()字典转换过去判断用户输入的内容'''
  23. args = vars(parser.parse_args())
  24. if args['list']:
  25. print lists()
  26. elif args['host']:
  27. print hosts(args['host'])
  28. else:
  29. parser.print_help()

用实际主机来跑一批任务

  1. ansible -i hosts.py docker -m ping -k

(3)主机文件支持的变量

ansible_ssh_host 定义host ssh地址

ansible_ssh_port 定义host ssh端口

ansible_ssh_user 定义hosts ssh认证用户

ansible_ssh_pass 定义hosts ssh 认证密码

ansible_sudo 定义hosts sudo用户

ansible_sudo_pass 定义hosts sudo密码

ansible_sudo_exe 定义hosts sudo 路径

ansible_connection 定义hosts连接方式

ansible_ssh_private_key_file 定义hosts私钥

ansible_shell_type 定义hosts shell类型

ansible_python_interpreter 定义hosts任务执行python路径

ansible_*_interpreter 定义hosts其他语言解析器路径

2.Ansible Ad-Hoc##

命令行方式使用ansible模块,使用ad-Hoc形式,插件功能无法使用,比如loop,facts功能

2.1命令模式(shell)###

1.普通同步模式等待后端返回结果的

  1. ansible -i /tmp/hosts docker -m shell -a 'uptime'

2.异步模式,放后台,每隔几秒去看下任务状态,取回来数据

  1. # -B 120 :把执行slee 10的任务放到后台120秒,超过120秒后就报超时了
  2. # -P 2: 放到后台后,每隔2秒去远程主机上获取下任务状态,有返回取回数据,没返回,隔2秒后再去取一次结果,直到都取完后,任务完成
  3. ansible -i /tmp/hosts docker -m shell -a 'sleep 10' -B 120 -P 2

异步原理:使用-P 参数后,会返回一个job_id,然后针对主机根据job_id去查询执行结果,每台主机产生不同的job_id,可以通过async_status模块查看异步任务的状态和结果,当-P 0的时候返回job_id就没了,后续操作需要自己去调用async_status模块取结果



如果-P 参数大于0,ansible会根据job_id去轮训查询执行结果

2.2.1复制文件(copy)###

  1. ansible -i /tmp/hosts webservers -m copy -a 'src=/tmp/hosts dest=/tmp/ owner=admin group=admin mode=644 backup=yes'

其余帮助参数如下

  1. [admin@host-10-187-196-225 tmp]$ ansible-doc -s copy
  2. less 436
  3. Copyright (C) 1984-2009 Mark Nudelman
  4. less comes with NO WARRANTY, to the extent permitted by law.
  5. For information about the terms of redistribution,
  6. see the file named README in the less distribution.
  7. Homepage: http://www.greenwoodsoftware.com/less
  8. - name: C o p i e s f i l e s t o r e m o t e l o c a t i o n s .
  9. action: copy
  10. backup # Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.
  11. content # When used instead of 'src', sets the contents of a file directly to the specified value.
  12. dest= # Remote absolute path where the file should be copied to. If src is a directory, this must be a directory too.
  13. 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 ar
  14. follow # This flag indicates that filesystem links, if they exist, should be followed.
  15. 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 desti
  16. group # name of the group that should own the file/directory, as would be fed to `chown'
  17. mode # mode the file or directory should be, such as 0644 as would be fed to `chmod'. As of version 1.8, the mode may be specified as a symbolic mode (for example, `
  18. owner # name of the user that should own the file/directory, as would be fed to `chown'
  19. 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'.
  20. serole # role part of SELinux file context, `_default' feature works as for `seuser'.
  21. setype # type part of SELinux file context, `_default' feature works as for `seuser'.
  22. 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 availab
  23. 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 w
  24. 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 exampl

2.2.2拽文件(fetch)###

把远程节点的/tmp/1.txt文件拽到本机/tmp/目录下,最后一定要/结尾,flat=yes代表的是直接以原文件名在/tmp/目录下命名创建

  1. [admin@host-10-187-196-225 tmp]$ ansible -i 1 all -m fetch -a "src=/tmp/1.txt dest=/tmp/ flat=yes" -k
  2. SSH password:
  3. 10.185.12.10 | success >> {
  4. "changed": true,
  5. "checksum": "52db334a166050298648cb3ba63336d9e9a9ac09",
  6. "dest": "/tmp/1.txt",
  7. "md5sum": "c41da816ae05a847b668da48bf8653d5",
  8. "remote_checksum": "52db334a166050298648cb3ba63336d9e9a9ac09",
  9. "remote_md5sum": null
  10. }

其余帮助参数

  1. [admin@host-10-187-196-225 tmp]$ ansible-doc -s fetch
  2. less 436
  3. Copyright (C) 1984-2009 Mark Nudelman
  4. less comes with NO WARRANTY, to the extent permitted by law.
  5. For information about the terms of redistribution,
  6. see the file named README in the less distribution.
  7. Homepage: http://www.greenwoodsoftware.com/less
  8. - name: F e t c h e s a f i l e f r o m r e m o t e n o d e s
  9. action: fetch
  10. dest= # A directory to save the file into. For example, if the `dest' directory is `/backup' a `src' file named `/etc/profile' on host `host.example.com', would be sa
  11. fail_on_missing # Makes it fails when the source file is missing.
  12. flat # Allows you to override the default behavior of prepending hostname/path/to/file to the destination. If dest ends with '/', it will use the basename of the so
  13. src= # The file on the remote system to fetch. This `must' be a file, not a directory. Recursive fetching may be supported in a later release.
  14. validate_checksum # Verify that the source and destination checksums match after the files are fetched.

dest:用来存放文件的目录,例如存放目录为backup,源文件名称为/etc/profile在主机pythonserver中,那么保存为/backup/pythonserver/etc/profile

Fail_on_missing:当源文件不存在的时候,标识为失败

Flat:允许覆盖默认行为从hostname/path到/file的,如果dest以/结尾,它将使用源文件的基础名称

Src:在远程拉取的文件,并且必须是一个file,不能是目录

Validate_checksum:当文件fetch之后进行md5检查

2.3包管理(yum)###

  1. ansible -i /tmp/hosts webservers -m yum -a 'name=mysql state=latest'

其余帮助文档

  1. > YUM
  2. Installs, upgrade, removes, and lists packages and groups with the
  3. `yum' package manager.
  4. Options (= is mandatory):
  5. - conf_file
  6. The remote yum configuration file to use for the transaction.
  7. [Default: None]
  8. - disable_gpg_check
  9. Whether to disable the GPG checking of signatures of packages
  10. being installed. Has an effect only if state is `present' or
  11. `latest'. (Choices: yes, no) [Default: no]
  12. - disablerepo
  13. `Repoid' of repositories to disable for the install/update
  14. operation. These repos will not persist beyond the
  15. transaction. When specifying multiple repos, separate them
  16. with a ",". [Default: None]
  17. - enablerepo
  18. `Repoid' of repositories to enable for the install/update
  19. operation. These repos will not persist beyond the
  20. transaction. When specifying multiple repos, separate them
  21. with a ",". [Default: None]
  22. - list
  23. Various (non-idempotent) commands for usage with
  24. `/usr/bin/ansible' and `not' playbooks. See examples.
  25. [Default: None]
  26. = name
  27. Package name, or package specifier with version, like
  28. `name-1.0'. When using state=latest, this can be '*' which
  29. means run: yum -y update. You can also pass a url or a local
  30. path to a rpm file. [Default: None]
  31. - state
  32. Whether to install (`present', `latest'), or remove (`absent')
  33. a package. (Choices: present, latest, absent) [Default:
  34. present]
  35. = name
  36. Package name, or package specifier with version, like
  37. `name-1.0'. When using state=latest, this can be '*' which
  38. means run: yum -y update. You can also pass a url or a local
  39. path to a rpm file. [Default: None]
  40. - state
  41. Whether to install (`present', `latest'), or remove (`absent')
  42. a package. (Choices: present, latest, absent) [Default:
  43. present]
  44. - update_cache
  45. Force updating the cache. Has an effect only if state is
  46. `present' or `latest'. (Choices: yes, no) [Default: no]
  47. Requirements: yum
  48. EXAMPLES:
  49. - name: install the latest version of Apache
  50. yum: name=httpd state=latest
  51. - name: remove the Apache package
  52. yum: name=httpd state=absent
  53. - name: install the latest version of Apache from the testing repo
  54. yum: name=httpd enablerepo=testing state=present
  55. - name: install one specific version of Apache
  56. yum: name=httpd-2.2.29-1.4.amzn1 state=present
  57. - name: upgrade all packages
  58. yum: name=* state=latest
  59. - name: install the nginx rpm from a remote repo
  60. yum: name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present
  61. - name: install nginx rpm from a local file
  62. yum: name=/usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present
  63. - name: install the 'Development tools' package group
  64. yum: name="@Development tools" state=present

2.4用户管理(user)###

  1. ansible -i /tmp/hosts webservers -m user -a 'name=diaodiao password="123456"'

其余帮助文档

  1. > USER
  2. Manage user accounts and user attributes.
  3. Options (= is mandatory):
  4. - append
  5. If `yes', will only add groups, not set them to just the list
  6. in `groups'. (Choices: yes, no) [Default: no]
  7. - comment
  8. Optionally sets the description (aka `GECOS') of user account.
  9. - createhome
  10. Unless set to `no', a home directory will be made for the user
  11. when the account is created or if the home directory does not
  12. exist. (Choices: yes, no) [Default: yes]
  13. - expires
  14. An expiry time for the user in epoch, it will be ignored on
  15. platforms that do not support this. Currently supported on
  16. Linux and FreeBSD. [Default: None]
  17. - force
  18. When used with `state=absent', behavior is as with `userdel
  19. --force'. (Choices: yes, no) [Default: no]
  20. - generate_ssh_key
  21. Whether to generate a SSH key for the user in question. This
  22. will *not* overwrite an existing SSH key. (Choices: yes, no)
  23. [Default: no]
  24. - group
  25. Optionally sets the user's primary group (takes a group name).
  26. - groups
  27. Puts the user in this comma-delimited list of groups. When set
  28. to the empty string ('groups='), the user is removed from all
  29. groups except the primary group.
  30. - home
  31. Optionally set the user's home directory.
  32. - login_class
  33. Optionally sets the user's login class for FreeBSD, OpenBSD
  34. and NetBSD systems.
  35. - move_home
  36. If set to `yes' when used with `home=', attempt to move the
  37. user's home directory to the specified directory if it isn't
  38. there already. (Choices: yes, no) [Default: no]
  39. = name
  40. Name of the user to create, remove or modify.
  41. - non_unique
  42. Optionally when used with the -u option, this option allows to
  43. change the user ID to a non-unique value. (Choices: yes, no)
  44. [Default: no]
  45. - password
  46. Optionally set the user's password to this crypted value. See
  47. the user example in the github examples directory for what
  48. this looks like in a playbook. The `FAQ
  49. <http://docs.ansible.com/faq.html#how-do-i-generate-crypted-
  50. passwords-for-the-user-module>`_ contains details on various
  51. ways to generate these password values. Note on Darwin system,
  52. this value has to be cleartext. Beware of security issues.
  53. - remove
  54. When used with `state=absent', behavior is as with `userdel
  55. --remove'. (Choices: yes, no) [Default: no]
  56. - shell
  57. Optionally set the user's shell.
  58. - ssh_key_bits
  59. Optionally specify number of bits in SSH key to create.
  60. [Default: 2048]
  61. - ssh_key_comment
  62. Optionally define the comment for the SSH key. [Default:
  63. ansible-generated on $HOSTNAME]
  64. - ssh_key_file
  65. Optionally specify the SSH key filename. If this is a relative
  66. filename then it will be relative to the user's home
  67. directory. [Default: .ssh/id_rsa]
  68. - ssh_key_passphrase
  69. Set a passphrase for the SSH key. If no passphrase is
  70. provided, the SSH key will default to having no passphrase.
  71. - ssh_key_type
  72. Optionally specify the type of SSH key to generate. Available
  73. SSH key types will depend on implementation present on target
  74. host. [Default: rsa]
  75. - state
  76. Whether the account should exist or not, taking action if the
  77. state is different from what is stated. (Choices: present,
  78. absent) [Default: present]
  79. - system
  80. When creating an account, setting this to `yes' makes the user
  81. a system account. This setting cannot be changed on existing
  82. users. (Choices: yes, no) [Default: no]
  83. - uid
  84. Optionally sets the `UID' of the user.
  85. - update_password
  86. `always' will update passwords if they differ. `on_create'
  87. will only set the password for newly created users. (Choices:
  88. always, on_create) [Default: always]
  89. Requirements: useradd, userdel, usermod
  90. EXAMPLES:
  91. # Add the user 'johnd' with a specific uid and a primary group of 'admin'
  92. - user: name=johnd comment="John Doe" uid=1040 group=admin
  93. # Add the user 'james' with a bash shell, appending the group 'admins' and 'developers' to the user's groups
  94. - user: name=james shell=/bin/bash groups=admins,developers append=yes
  95. # Remove the user 'johnd'
  96. - user: name=johnd state=absent remove=yes
  97. # Create a 2048-bit SSH key for user jsmith in ~jsmith/.ssh/id_rsa
  98. # added a consultant whose account you want to expire
  99. - user: name=james18 shell=/bin/zsh groups=developers expires=1422403387

3.Ansible facts##

facts组件呢是ansible用于采集被管理机器设备信息的一个功能,可以使用setup检查机器的所有facts信息,用filter来查看指定信息.返回一个大json

  1. ansible -i /tmp/hosts webservers -m setup

Ansible自动化运维笔记2(Ansible的组件介绍)的更多相关文章

  1. Ansible自动化运维笔记1(安装配置)

    1.Ansible的安装 pip install ansible==1.9.1 ansible1.9.1版本依赖的软件有 Python2.6以上版本 paramiko模块 PyYAML Jinja2 ...

  2. Ansible自动化运维笔记3(playbook)

    1.基本语法 playbook文件格式为yaml语法.示例如下: 1.1 nginx.yaml --- - hosts: all tasks: - name: Install Nginx Packag ...

  3. ansible 自动化运维

    Ansible 自动化运维 ansible安装epel #yum list all *ansible*#yum install *ansible*#yum info ansible#rpm -ql a ...

  4. 自动化运维工具之ansible

    自动化运维工具之ansible   一,ansible简介 ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具(puppet.cfengine.chef.func.fab ...

  5. 自动化运维工具之 Ansible 介绍及安装使用

    一.初识Ansible 介绍: Absible 使用 模块(Modules)来定义配置任务.模块可以用标准脚本语言(Python,Bash,Ruby,等等)编写,这是一个很好的做法,使每个模块幂等.A ...

  6. ansible自动化运维

    ansible 系统架构 ansible简介 ansible是新出现的自动化运维工具,ansible是一个配置管理和应用部署工具,基于Python开发,集合了众多运维工具(puppet.cfengin ...

  7. Ansible自动化运维工具-上

    [Ansible特点] 1)Ansible与saltstack均是基于Python语言开发的 2)安装使用简单,基于不同插件和模块实现各种软件,平台,版本的管理以及支持虚拟容器多层级的部署 3)不需要 ...

  8. Ansible 自动化运维工具

    Ansible 自动化运维工具 Ansible是什么? Ansible是一个"配置管理工具"也是一个"自动化运维工具" Ansible 作用: Ansible是 ...

  9. ansible自动化运维03

    ansible自动化运维常用模块 常用模块实现的功能:安装软件包:修改配置文件:创建程序用户组:创建目录,并修改所属和权限:挂载:启动服务:测试. command模块: shell模块: 注意:com ...

随机推荐

  1. 定时任务schedule(spring boot )

    1. 定时任务实现方式:SpringBoot自带的Scheduled,可以将它看成一个轻量级的Quartz,而且使用起来比Quartz简单许多,本文主要介绍. 执行方式:单线程(串行)多线程(并行) ...

  2. Java数据结构和算法(十四)——堆

    在Java数据结构和算法(五)——队列中我们介绍了优先级队列,优先级队列是一种抽象数据类型(ADT),它提供了删除最大(或最小)关键字值的数据项的方法,插入数据项的方法,优先级队列可以用有序数组来实现 ...

  3. Servlet 浅析

    在我们学习Servlet之前,有必要了解一下Web容器的工作模式 我们所有的请求其实都是先到达了web容器,然后才分发给已经注册好的Servlet 请求由Servlet的service方法调用doGe ...

  4. window对象的属性

    还不是很了解,以后补充frames      opener       parent

  5. js发展历史

    1992年Nombas开发和醋C-minus-minus(c--),的嵌入式脚本语言,最初是绑定在Cenvi软件中,后将其改名scriptEase(客户端执行的语言) Netscape 接受Nomba ...

  6. 关键字voltale

    ***volatile在多线程用的最多.*** #include<stdio.h> #include<stdlib.h> int main() { ; i < ; i++ ...

  7. Java并发系列[4]----AbstractQueuedSynchronizer源码分析之条件队列

    通过前面三篇的分析,我们深入了解了AbstractQueuedSynchronizer的内部结构和一些设计理念,知道了AbstractQueuedSynchronizer内部维护了一个同步状态和两个排 ...

  8. React-Native 系列视频失效补链及一些碎碎念

    最近很多朋友联系我要视频链接,说失效了,这边补一下链接,时间问题就不一篇一篇修改了: 链接:https://pan.baidu.com/s/1mj5Cak4 密码:wiq2 注:视频还是建议参考,因为 ...

  9. Spring源码情操陶冶-PathMatchingResourcePatternResolver路径资源匹配溶解器

    本文简单的分析下spring对某个目录下的class资源是如何做到全部的加载 PathMatchingResourcePatternResolver#getResources PathMatching ...

  10. Linux history命令

    history命令主要用于显示历史命令, 重新执行历史命令. Linux系统当你在shell(控制台)中输入并执行命令时,shell会自动把你的命令记录到历史列表中,一般保存在用户目录下的.bash_ ...