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

[经验分享] ansible 番外篇之模块

[复制链接]

尚未签到

发表于 2018-1-2 14:39:00 | 显示全部楼层 |阅读模式
1. 内置模块
  是由 ansible 包装后, 在主机上执行一系列操作的脚本.

1.1 查看模块帮助
  

$ ansible-doc MOD_NAME  

1.2 查找第三方模块
  

$ ansible-galaxy search MOD_NAME  

1.3 常用模块

apt


  •   update_cache=yes

    在安装软件之前, 首先更新 repo 缓存.
  •   cache_valid_time=3600

    上次 repo 缓存的有效时间.
  •   upgrade=yes

pip
  Ansible 的 pip 模块支持向 virtualenv 中安装软件包, 并且还支持在没有可用的 virtualenv 时, 自动创建一个.
  

- name: install required python packages  pip: name={{ item }} virtualenv={{ venv_path }}
  with_items:
  - gunicorn
  - django
  - django-compressor
  

  支持 requirements 文件
  

- name: install required python pkg  pip: requirements={{ proj_path }}/{{ reqs_file }} virtualenv={{ venv_path }}
  

  Options :


  • chdir  
    cd into this directory before running the command
      
    [Default: None]

  • editable  
    Pass the editable flag for versioning URLs.
      
    [Default: True]

  • executable  
    The explicit executable or a pathname to the executable to be used to run pip for a specific
      
    version of Python installed in the system. For example `pip-3.3', if there are both Python 2.7
      
    and 3.3 installations in the system and you want to run pip for the Python 3.3 installation. It
      
    cannot be specified together with the 'virtualenv' parameter (added in 2.1). By default, it
      
    will take the appropriate version for the python interpreter use by ansible, e.g. pip3 on
      
    python 3, and pip2 or pip on python 2.
      
    [Default: None]

  • extra_args  
    Extra arguments passed to pip.
      
    [Default: None]

  • name  
    The name of a Python library to install or the url of the remote package.
      
    As of 2.2 you can supply a list of names.
      
    [Default: None]

  • requirements  
    The path to a pip requirements file, which should be local to the remote system. File can be
      
    specified as a>  
    [Default: None]

  • state  
    The state of module
      
    The 'forcereinstall' option is only available in Ansible 2.1 and above.
      
    (Choices: present, absent, latest, forcereinstall)[Default: present]

  • umask  
    The system umask to apply before installing the pip package. This is useful, for example, when
      
    installing on systems that have a very restrictive umask by default (e.g., 0077) and you want
      
    to pip install packages which are to be used by all users. Note that this requires you to
      
    specify desired umask mode in octal, with a leading 0 (e.g., 0077).
      
    [Default: None]

  • version  
    The version number to install of the Python library specified in the `name' parameter
      
    [Default: None]

  • virtualenv  
    An optional path to a `virtualenv' directory to install into. It cannot be specified together
      
    with the 'executable' parameter (added in 2.1). If the virtualenv does not exist, it will be
      
    created before installing packages. The optional virtualenv_site_packages, virtualenv_command,
      
    and virtualenv_python options affect the creation of the virtualenv.
      
    [Default: None]

  • virtualenv_command  
    The command or a pathname to the command to create the virtual environment with. For example
      
    pyvenv',virtualenv', virtualenv2',~/bin/virtualenv', `/usr/local/bin/virtualenv'.
      
    [Default: virtualenv]

  • virtualenv_python  
    The Python executable used for creating the virtual environment. For example python3.5',python2.7'. When not specified, the Python version used to run the ansible module is used.
      
    [Default: None]

  • virtualenv_site_packages  
    Whether the virtual environment will inherit packages from the global site-packages directory.
      
    Note that if this setting is changed on an already existing virtual environment it will not
      
    have any effect, the environment must be deleted and newly created.
      
    (Choices: yes, no)[Default: no]

copy

file

service

template

setup
  实现 fact 收集的模块. 一般无需再 playbook 中调用该模块, Ansible 会在采集 fact 时, 自动调用.
  $ ansible server_name -m setup -a 'filter=ansible_eth*'
  其返回值为一个字典, 字典的 key 是 ansible_fact, 他的 value 是一个有实际 fact 的名字与值组成的字典.
  setup 模块支持 filter 参数, 可以实现 shell 通配符的匹配过滤.
  

- name: gather facts  setup:
  

set_fact
  使用 set_fact 模块在 task 中设置 fact(与定义一个新变量是一样的). 可以在 register 关键字后, 立即使用 set_fact , 这样使得变量引用更简单.
  

- name: get snapshot>shell: >
  aws ec2 describe-snapshot --filters Name=tag:Name, Valuse=my-snapshot | jq --raw-outpuy ".Snapshots[].SnapshtId"
  register: snap_result
  
- set_fact: snap={{ snap_result.stdout }}
  

  
- name: delete old snapshot
  command: aws ec2 delete-snapshot --snapshot-id "{{ snap }}"
  

command
  在 command 中保持幂等性的方法: 指定 creates 参数.
  

# 当 Vagrantfile 存在, 则表示已经处于正确状态, 而且不需要再次执行命令, 从而实现幂等性.  
- name: create a vagrantfile
  command: vagrant init {{ box }} creates=Vagrantfile
  

  官方文档:
  

- creates  a filename or (since 2.0) glob pattern, when it already exists, this step
  will *not* be run.
[Default: None]

  

  
- removes
  a filename or (since 2.0) glob pattern, when it does not exist, this step
  will *not* be run.
[Default: None]

  

script
  实现幂等性方法: creates 和 removes 参数.
  官方文档:
  

- creates  a filename, when it already exists, this step will *not* be run.
[Default: None]

  

  
- removes
  a filename, when it does not exist, this step will *not* be run.
[Default: None]

  

debug
  

> DEBUG    (/opt/virtualEnv/ansibleEnv/lib/python2.7/site-packages/ansible/modules/utilities/logic/debug.py)  

  This module prints statements during execution and can be useful for debugging variables or
  expressions without necessarily halting the playbook. Useful for debugging together with the 'when:'
  directive.
  

  * note: This module has a corresponding action plugin.
  

  
Options (= is mandatory):
  

  
- msg
  The customized message that is printed. If omitted, prints a generic message.
[Default: Hello world!]

  
- var
  A variable name to debug.  Mutually exclusive with the 'msg' option.
[Default: (null)]

  
- verbosity
  A number that controls when the debug is run, if you set to 3 it will only run debug when -vvv
  or above
[Default: 0]

  

  
EXAMPLES:
  

  
# Example that prints the loopback address and gateway for each host
  
- debug:
  msg: "System {{ inventory_hostname }} has uuid {{ ansible_product_uuid }}"
  

  
- debug:
  msg: "System {{ inventory_hostname }} has gateway {{ ansible_default_ipv4.gateway }}"
  when: ansible_default_ipv4.gateway is defined
  

  
- shell: /usr/bin/uptime
  register: result
  

  
- debug:
  var: result
  verbosity: 2
  

  
- name: Display all variables/facts known for a host
  debug:
  var: hostvars[inventory_hostname]
  verbosity: 4
  

postgresql_user

postgresql_db

django_manage

cron :
  

# 安装 cron job, 注意 name 参数, 该参数必须要有, 该参数将用于删除计划任务时所使用的名称.  
- name: install poll twitter cron job
  cron: name="Poll twitter" minute="*/5" user={{ user }} job="{{ manage }} poll_twitter"
  

  
# 删除计划任务, 基于 name 参数, 在删除时, 会连带注释一起删掉.
  
- name: remote cron job
  cron: name="Poll twitter" state=absent
  

git :
  

- name: check out the repository on the host  git: repo={{ repo_url }} dest={{ proj_path }} accept_host_key=yes
  

wait_for:
  You can wait for a set amount of time `timeout', this is the default if nothing is specified. Waiting for a port to become available is useful for when services are not immediately available after their init scripts return which is true of certain Java application servers. It is also useful when starting guests with the [virt] module and needing to pause until they are ready. This module can also be used to wait for a regex match a string to be present in a file.
  In 1.6 and later, this module can also be used to wait for a file to be available or absent on the filesystem.
  In 1.8 and later, this module can also be used to wait for active connections to be closed before continuing,useful if a node is being rotated out of a load balancer pool.
  Options:


  • active_connection_states  
    The list of tcp connection states which are counted as active connections
      
    [Default: [u'ESTABLISHED', u'SYN_SENT', u'SYN_RECV', u'FIN_WAIT1', u'FIN_WAIT2', u'TIME_WAIT']]

  • connect_timeout  
    maximum number of seconds to wait for a connection to happen before closing and retrying
      
    [Default: 5]

  • delay  
    number of seconds to wait before starting to poll
      
    [Default: 0]

  • exclude_hosts  
    list of hosts or IPs to ignore when looking for active TCP connections for `drained' state
      
    [Default: None]

  • host  
    A resolvable hostname or IP address to wait for
      
    [Default: 127.0.0.1]

  • path  
    path to a file on the filesytem that must exist before continuing
      
    [Default: None]

  • port  
    port number to poll
      
    [Default: None]

  • search_regex  
    Can be used to match a string in either a file or a socket connection. Defaults to a multiline
      
    regex.
      
    [Default: None]

  • sleep  
    Number of seconds to sleep between checks, before 2.3 this was hardcoded to 1 second.
      
    [Default: 1]

  • state  
    either present',started', or stopped',absent', or drained'     When checking a portstarted' will ensure the port is open, stopped' will check that it is     closed,drained' will check for active connections
      
    When checking for a file or a search string present' orstarted' will ensure that the file or
      
    string is present before continuing, `absent' will check that file is absent or removed
      
    (Choices: present, started, stopped, absent, drained)[Default: started]

  • timeout  
    maximum number of seconds to wait for
      
    [Default: 300]

lineinfile

stat
  收集关于文件路径状态的各种信息, 返回一个字典, 该字典包含一个 stat 字段. 部分字段返回值表:

字段
描述
dev
inode 所在设备>assert
  assert 模块在指定的条件不符合是,返回错误, 并失败退出. 主要用于调试.
  
that : 后跟计算表达式
  
msg : 失败后的提示信息.
  

- name: stat /opt/foo  stat: path=/opt/foo
  register: st
  

  
- name: assert that /opt/foo is a directory
  assert:
  that: st.stat.isdir
  

  
-------
  

  
- assert:
  that:
  - &quot;my_param <= 100&quot;
  - &quot;my_param >= 0&quot;
  msg: &quot;'my_param' must be between 0 and 100&quot;
  

2. 自定义模块
  自定义模块存放路径: playbooks/library

2.1 使用 script 自定义 模块

2.2 使用 Python 自定义模块.

运维网声明 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-430829-1-1.html 上篇帖子: Ansible Playbooks高级使用 下篇帖子: Ansible Inventory篇
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

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

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

扫描微信二维码查看详情

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


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


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


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



合作伙伴: 青云cloud

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