文件操作

文件创建

  • file

用于设置文件/链接/目录的属性,或者删除文件/链接/目录

  1. ### state如果是directory当目录不存在时会自动创建;如果是file当文件不存在时不会自动创建
  2. - name: Create log dir
  3. file:
  4. path: "{{ item.src }}"
  5. state: directory
  6. with_items: "{{ log_dirs }}"
  7. when: is_metal | bool
  8. tags:
  9. - common-log
  10. - name: Mask lxc-net systemd service
  11. file:
  12. src: /dev/null
  13. path: /etc/systemd/system/lxc-net.service
  14. state: link
  15. when:
  16. - ansible_service_mgr == 'systemd'
  17. tags:
  18. - lxc-files
  19. - lxc-net

修改文件

  • lineinfile

用于检测文件是否存在特殊行或者使用后端正则表达式来替换匹配到的特殊行

  1. - name: Extra lxc config
  2. lineinfile:
  3. dest: "/var/lib/lxc/{{ inventory_hostname }}/config"
  4. line: "{{ item.split('=')[0] }} = {{ item.split('=', 1)[1] }}"
  5. insertafter: "^{{ item.split('=')[0] }}"
  6. backup: "true"
  7. with_items: "{{ extra_container_config | default([]) }}"
  8. delegate_to: "{{ physical_host }}"
  9. register: _ec
  10. when: not is_metal | bool
  11. tags:
  12. - common-lxc
  • replace

lineinfile的多行匹配版本,此模块会在文件中插入一段内容,并在内容开始和结束位置设置标签,后续可以使用标签可以对此块内容进行操作

  1. ### 在ml2_conf.ini文件的[ml2]和[ml2_type_vlan]字段之间插入一段内容
  2. - name: Enable ovn in neutron-server
  3. replace:
  4. dest: "{{ node_config_directory }}/neutron-server/ml2_conf.ini"
  5. regexp: '\[ml2\][\S\s]*(?=\[ml2_type_vlan\])'
  6. replace: |+
  7. [ml2]
  8. type_drivers = local,flat,vlan,geneve
  9. tenant_network_types = geneve
  10. mechanism_drivers = ovn
  11. extension_drivers = port_security
  12. overlay_ip_version = 4
  13. [ml2_type_geneve]
  14. vni_ranges = 1:65536
  15. max_header_size = 38
  16. [ovn]
  17. ovn_nb_connection = tcp:{{ api_interface_address }}:{{ ovn_northdb_port }}
  18. ovn_sb_connection = tcp:{{ api_interface_address }}:{{ ovn_sourthdb_port }}
  19. ovn_l3_mode = False
  20. ovn_l3_scheduler = chance
  21. ovn_native_dhcp = True
  22. neutron_sync_mode = repair
  23. backup: yes
  24. when:
  25. - action == "deploy"
  26. - inventory_hostname in groups['network']
  27. notify:
  28. - Restart neutron-server container
  • ini_file

ini后缀格式文件修改

  1. ### 设置l3_agent.ini文件[DEFAULT]字段的external_network_bridge选项值为br-ex
  2. - name: Set the external network bridge
  3. vars:
  4. agent: "{{ 'neutron-vpnaas-agent' if enable_neutron_vpnaas | bool else 'neutron-l3-agent' }}"
  5. ini_file:
  6. dest: "{{ node_config_directory }}/{{ agent }}/l3_agent.ini"
  7. section: "DEFAULT"
  8. option: "external_network_bridge"
  9. value: "{{ neutron_bridge_name | default('br-ex') }}"
  10. backup: yes
  11. when:
  12. - action == "deploy"
  13. - inventory_hostname in ovn_central_address
  14. delegate_to: "{{ item }}"
  15. with_items: "{{ groups['neutron-server'] }}"
  16. notify:
  17. - Restart {{ agent }} container
  • assemble

将多个文件聚合成一个文件

  1. ### 将/etc/haproxy/conf.d目录下的文件内容聚合成/etc/haproxy/haproxy.cfg文件
  2. - name: Regenerate haproxy configuration
  3. assemble:
  4. src: "/etc/haproxy/conf.d"
  5. dest: "/etc/haproxy/haproxy.cfg"
  6. notify: Restart haproxy
  7. tags:
  8. - haproxy-general-config

循环控制

  • with_items

标准循环,用于执行重复任务,{{ item }}类似宏展开

  1. - name: add several users
  2. user:
  3. name: "{{ item.name }}"
  4. state: present
  5. groups: "{{ item.groups }}"
  6. with_items:
  7. - { name: 'testuser1', groups: 'wheel' }
  8. - { name: 'testuser2', groups: 'root' }
  • with_nested

嵌套循环

  1. ### 修改neutron-server组所有主机的ml2_conf.ini文件的对应字段值
  2. - name: Enable ovn in neutron-server
  3. vars:
  4. params:
  5. - { section: 'ml2', option: 'type_drivers', value: 'local,flat,vlan,geneve' }
  6. - { section: 'ml2', option: 'tenant_network_types', value: 'geneve' }
  7. - { section: 'ml2', option: 'mechanism_drivers', value: 'ovn' }
  8. - { section: 'ml2', option: 'extension_drivers', value: 'port_security' }
  9. - { section: 'ml2', option: 'overlay_ip_version', value: '4' }
  10. - { section: 'securitygroup', option: 'enable_security_group', value: 'True' }
  11. ini_file:
  12. dest: "{{ node_config_directory }}/neutron-server/ml2_conf.ini"
  13. section: "{{ item[0].section }}"
  14. option: "{{ item[0].option }}"
  15. value: "{{ item[0].value }}"
  16. backup: yes
  17. when:
  18. - action == "deploy"
  19. - inventory_hostname in ovn_central_address
  20. delegate_to: "{{ item[1] }}"
  21. with_nested:
  22. - "{{ params }}"
  23. - "{{ groups['neutron-server'] }}"
  24. notify:
  25. - Restart neutron-server container

流程控制

  • tags

设置任务标签

  1. tasks:
  2. - yum: name={{ item }} state=installed
  3. with_items:
  4. - httpd
  5. - memcached
  6. tags:
  7. - packages
  8. - template: src=templates/src.j2 dest=/etc/foo.conf
  9. tags:
  10. - configuration
  11. ### 执行playbook可以指定只执行标签对应任务或跳过标签对应任务
  12. # ansible-playbook example.yml --tags "configuration,packages"
  13. # ansible-playbook example.yml --skip-tags "notification"
  • fail_when

用来控制playbook退出

  1. - name: Check if firewalld is installed
  2. command: rpm -q firewalld
  3. register: firewalld_check
  4. failed_when: firewalld_check.rc > 1
  5. when: ansible_os_family == 'RedHat'
  • pre_tasks/post_tasks

用来设置在执行roles模块之前和之后需要执行的任务

  1. - name: Install the aodh components
  2. hosts: aodh_all
  3. gather_facts: "{{ gather_facts | default(True) }}"
  4. max_fail_percentage: 20
  5. user: root
  6. pre_tasks:
  7. - include: common-tasks/os-lxc-container-setup.yml
  8. - include: common-tasks/rabbitmq-vhost-user.yml
  9. static: no
  10. vars:
  11. user: "{{ aodh_rabbitmq_userid }}"
  12. password: "{{ aodh_rabbitmq_password }}"
  13. vhost: "{{ aodh_rabbitmq_vhost }}"
  14. _rabbitmq_host_group: "{{ aodh_rabbitmq_host_group }}"
  15. when:
  16. - inventory_hostname == groups['aodh_api'][0]
  17. - groups[aodh_rabbitmq_host_group] | length > 0
  18. - include: common-tasks/os-log-dir-setup.yml
  19. vars:
  20. log_dirs:
  21. - src: "/openstack/log/{{ inventory_hostname }}-aodh"
  22. dest: "/var/log/aodh"
  23. - include: common-tasks/mysql-db-user.yml
  24. static: no
  25. vars:
  26. user_name: "{{ aodh_galera_user }}"
  27. password: "{{ aodh_container_db_password }}"
  28. login_host: "{{ aodh_galera_address }}"
  29. db_name: "{{ aodh_galera_database }}"
  30. when: inventory_hostname == groups['aodh_all'][0]
  31. - include: common-tasks/package-cache-proxy.yml
  32. roles:
  33. - role: "os_aodh"
  34. aodh_venv_tag: "{{ openstack_release }}"
  35. aodh_venv_download_url: "{{ openstack_repo_url }}/venvs/{{ openstack_release }}/{{ ansible_distribution | lower }}/aodh-{{ openstack_release }}-{{ ansible_architecture | lower }}.tgz"
  36. - role: "openstack_openrc"
  37. tags:
  38. - openrc
  39. - role: "rsyslog_client"
  40. rsyslog_client_log_rotate_file: aodh_log_rotate
  41. rsyslog_client_log_dir: "/var/log/aodh"
  42. rsyslog_client_config_name: "99-aodh-rsyslog-client.conf"
  43. tags:
  44. - rsyslog
  45. vars:
  46. is_metal: "{{ properties.is_metal|default(false) }}"
  47. aodh_rabbitmq_userid: aodh
  48. aodh_rabbitmq_vhost: /aodh
  49. aodh_rabbitmq_servers: "{{ rabbitmq_servers }}"
  50. aodh_rabbitmq_port: "{{ rabbitmq_port }}"
  51. aodh_rabbitmq_use_ssl: "{{ rabbitmq_use_ssl }}"
  52. tags:
  53. - aodh

主机路由

  • delegate_to

可以将当前任务放到其他hosts上执行

  1. ### 这是一段在容器中执行的playbook的一部分,这时候需要检测容器所在的宿主机上的对应目录是否存在,这时候就需要用到委托来跳出当前容器到宿主机上执行当前任务
  2. - name: Ensure mount directories exists
  3. file:
  4. path: "{{ item['mount_path'] }}"
  5. state: "directory"
  6. with_items:
  7. - "{{ lxc_default_bind_mounts | default([]) }}"
  8. - "{{ list_of_bind_mounts | default([]) }}"
  9. delegate_to: "{{ physical_host }}"
  10. when:
  11. - not is_metal | bool
  12. tags:
  13. - common-lxc
  • local_action

将任务放在ansible控制主机(运行ansible-playbook的主机)上执行

  1. - name: Check if the git cache exists on deployment host
  2. local_action:
  3. module: stat
  4. path: "{{ repo_build_git_cache }}"
  5. register: _local_git_cache
  6. when: repo_build_git_cache is defined

用户和用户组控制

  • group

创建用户组

  1. ### 创建系统管理员组haproxy,present表示不存在创建,absent表示存在删除
  2. - name: Create the haproxy system group
  3. group:
  4. name: "haproxy"
  5. state: "present"
  6. system: "yes"
  7. tags:
  8. - haproxy-group
  • user

创建用户

  1. ### 创建haproxy:haproxy用户,并创建home目录
  2. - name: Create the haproxy system user
  3. user:
  4. name: "haproxy"
  5. group: "haproxy"
  6. comment: "haproxy user"
  7. shell: "/bin/false"
  8. system: "yes"
  9. createhome: "yes"
  10. home: "/var/lib/haproxy"
  11. tags:
  12. - haproxy-user

其他

  • authorized_key

添加用户的SSH认证key

  1. - name: Create authorized keys file from host vars
  2. authorized_key:
  3. user: "{{ repo_service_user_name }}"
  4. key: "{{ hostvars[item]['repo_pubkey'] | b64decode }}"
  5. with_items: "{{ groups['repo_all'] }}"
  6. when: hostvars[item]['repo_pubkey'] is defined
  7. tags:
  8. - repo-key
  9. - repo-key-store
  • slurp

用来读取远程主机上文件内容是base64加密的文件

  1. ### 读取id_rsa.pub文件的内容,并设置到变量repo_pub中
  2. - name: Get public key contents and store as var
  3. slurp:
  4. src: "{{ repo_service_home_folder }}/.ssh/id_rsa.pub"
  5. register: repo_pub
  6. changed_when: false
  7. tags:
  8. - repo-key
  9. - repo-key-create
  • uri

web访问,类似执行curl命令

  1. - name: test proxy URL for connectivity
  2. uri:
  3. url: "{{ repo_pkg_cache_url }}/acng-report.html"
  4. method: "HEAD"
  5. register: proxy_check
  6. failed_when: false
  7. tags:
  8. - common-proxy
  • wait_for

等待一个端口变得可用或者等待一个文件变得可用

  1. - name: Wait for container ssh
  2. wait_for:
  3. port: "22"
  4. delay: "{{ ssh_delay }}"
  5. search_regex: "OpenSSH"
  6. host: "{{ ansible_host }}"
  7. delegate_to: "{{ physical_host }}"
  8. register: ssh_wait_check
  9. until: ssh_wait_check | success
  10. retries: 3
  11. when:
  12. - (_mc is defined and _mc | changed) or (_ec is defined and _ec | changed)
  13. - not is_metal | bool
  14. tags:
  15. - common-lxc
  • command

执行shell命令

  1. ### ignore_errors为true表示命令执行出错也不会退出playbook
  2. - name: Check if clean is needed
  3. command: docker exec openvswitch_vswitchd ovs-vsctl br-exists br-tun
  4. register: result
  5. ignore_errors: True

切换用户

  1. ### 使用become会先切换成apache用户,再执行command命令,默认become_user用户为root(如果你ansible配置的就是root用户的免密码登入那就不需要become了)
  2. - name: Run a command as the apache user
  3. command: somecommand
  4. become: true
  5. become_user: apache

检测链表是否为空

  1. ### pip_wheel_install为链表变量
  2. - name: Install wheel packages
  3. shell: cd /tmp/wheels && pip install {{ item }}*
  4. with_items:
  5. - "{{ pip_wheel_install | default([]) }}"
  6. when: pip_wheel_install > 0

Ansible Playbooks高级使用的更多相关文章

  1. 3、Ansible playbooks(Hosts、Users、tasks、handlers、变量、条件测试(when、迭代)、templates)

    Ansible playbooks playbook是由一个或多个“play”组成的列表.play的主要功能在于将事先归并为一组的主机装扮成事先通过ansible中的task定义好的角色.从根本上来讲 ...

  2. Ansible Playbooks 介绍 和 使用 二

    目录 handlers playbook 案例 2 handlers vars 变量 setup facts 变量使用 案例 inventory 中定义变量 案例 条件测试 when 语句 案例 迭代 ...

  3. Ansible Playbooks 介绍 和 使用 一

    目录 Ansible Playbooks Playbooks 组成部分: YAML 介绍 YAML 语法 Ansible 基础元素 变量 facts registre 通过命令传递变量 通过roles ...

  4. Ansible playbooks

    Playbook是Ansible的配置,部署和编排语言. 他们可以描述您希望远程系统执行的策略,或一般IT流程中的一组步骤. 如果Ansible modules是您workshop的工具,则playb ...

  5. Ansible playbooks(任务、角色、模板、变色器、)

    playbooks配置文件: [root@ansible ~]# vim /etc/ansible/hosts [test01] 192.168.200.114 [test02] 192.168.20 ...

  6. ansible的高级应用-roles

    在之前我们知道了playbook,类似于shell的脚本,playbook适用于一些不太麻烦的部署任务,比如说使用playbook安装mysql,那么我们直接写一个playbook文件即可.可是如果我 ...

  7. Ansible Playbooks 常用模块

    官网链接:https://docs.ansible.com/ansible/latest/modules/list_of_all_modules.html ansible python module ...

  8. Ansible Playbooks入门介绍

    1.目录结构 2.详细目录 3.主任务文件main.yaml 主任务文件main.yaml - name: print server name and user to remote testbox # ...

  9. Ansible Playbooks基本使用

    你将学到什么 如何使用playbook 如何编写playbook 如何使用roles PlayBook使用 基础环境 ### 64 位 Ubuntu 16.04 LTS,创建CentOS LXC容器w ...

随机推荐

  1. Jquery Uploadify多文件上传实例

    jQuery Uploadify开发使用的语言是java. 详细的相关文档,可以参考官网的doc:http://www.uploadify.com/documentation/ 官网的讲解还是很详细的 ...

  2. Codeforces 337D Book of Evil:树的直径【结论】

    题目链接:http://codeforces.com/problemset/problem/337/D 题意: 给你一棵树,n个节点. 如果一个节点处放着“罪恶之书”,那么它会影响周围距离不超过d的所 ...

  3. Saiku_学习_02_Schema Workbench 开发mdx和模式文件

    一.前言 saiku的查询都是通过cube来进行的.因此每当我们要进行一次多维度查询时,都要先修改xml.上传.重启才能生效,不仅效率低,还不利于学习和理解MDX和模式文件. 通过 workbench ...

  4. 【Codeforces Round #466】E. Cashback DP+ST表

    题意 给定$n$个数,将其划分成若干个连续的子序列,求最小价值,数组价值定义为,数组和减去$\lfloor \frac{k}{c} \rfloor$,$k$为数组长度,$c$为给定数 可以列得朴素方程 ...

  5. 关于c++中局部变量和全局变量的存储位置及内存回收机制

    局部变量,参数变量存放在栈中,当离开作用范围后,分配的内存在作用范围外会被系统自动回收. new出来的内存空间存放在堆中,不受作用域管理,不会被系统自动回收,只有在使用delete删除或者整个程序结束 ...

  6. codeforces 637A A. Voting for Photos(水题)

    题目链接: A. Voting for Photos time limit per test 1 second memory limit per test 256 megabytes input st ...

  7. fedora使用mac osx字体和渲染方式

    fedora 19的倒退(中文显示有问题)让人感到很沮丧,不过,后来还是找到了一个很好的解决方案:使用max osx的字体和渲染方式 1. 安装infinality字体渲染软件: rpm -Uvh h ...

  8. 使用 Anthem.NET 的经验小结

    1. 不依靠 Panel 来做省事的区域性 Ajax. 2. 控件不要图偷懒设置 AutoUpdateAfterCallBack = true. 而是每次需要更新的时候指定 UpdateAfterCa ...

  9. [转]angularjs的provider~ (Provider, Value, Constant, Service, Factory, Decorator)

    用AngularJS做项目,但凡用过什么service啊,factory啊,provider啊,开始的时候晕没晕?!晕没晕?!感觉干的事儿都差不多啊,到底用哪个啊?!别告诉我你们几个就是为了跟我炫耀兄 ...

  10. Maven运行JUnit测试(http://www.360doc.com/content/13/0927/15/7304817_317455642.shtml)

    Maven单元测试 分类: maven 2012-05-09 15:17 1986人阅读 评论(1) 收藏 举报 maven测试junit单元测试javarandom   目录(?)[-] maven ...