ansible学习笔记03

网友投稿 934 2022-09-04

ansible学习笔记03

ansible学习笔记03

playbook剧本文件

playbook,剧本文件,相比较ad hoc而言,playbook文件一次能执行多个任务,就像是连续剧一样,第一段、第二段……第n段,每个剧情的情节自己可以设定,语法比较简单,容易学习。 实验准备工作 # 新建一个文件夹存放playbook [student@workstation ~]$ mkdir deploy-playbook-test

准备工作,ansible配置文件和inventory清单文件

[student@workstation deploy-playbook-test]$ cat ansible.cfg[defaults]inventory = ./inventoryask_pass = false

[privilege_escalation]become = truebecome_method = sudobecome_user = rootbecome_ask_pass = false[student@workstation deploy-playbook-test]$ cat inventoryservera[home]serveraserverbservercserverd

## 1、 playbook文件的基本语法规则 > 1、 playbook文件以.yaml或.yml结尾 > > 2、 playbook文件是有层级关系的,越靠近左侧,层级越高 ## 2、 第一个playbook ```yml [student@workstation deploy-playbook-test]$ cat user.yml --- - name: 新建一个用户 hosts: servera tasks: - name: 新建一个用户mmx user: name: mmx uid: 1200 state: present

2.1 第一级的含义如下所示

参数 含义
--- ansible-play文件的开始
- name 用于说明该playbook的含义(可省略,但不建议省略)
hosts 说明在哪些主机上执行play文件
tasks 需要执行的任务
... 以...结束playbook文件,可以省略(我也省略掉了,没在演示中写出来)

2.2 剩余层级含义

参数 含义
name 介绍使用模块干什么
user 使用模块名称
name、uid、state user下的参数

2.3 playbook文件语法检查

格式: ansible-playbook --syntax-check user.yml

语法检查没有问题返回:playbook: xxx.yml

[student@workstation deploy-playbook-test]$ ansible-playbook --syntax-check user.yml playbook: user.yml

2.4 playbook文件尝试运行

格式: ansible-playbook -C user.yml

[student@workstation deploy-playbook-test]$ ansible-playbook -C user.yml PLAY [新建一个用户] ************************************************************************************************************************************************ TASK [Gathering Facts] *************************************************************************************************************************************** ok: [servera] TASK [新建一个用户mmx] ********************************************************************************************************************************************* ok: [servera] PLAY RECAP *************************************************************************************************************************************************** servera : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 # 发现尝试运行没有问题

2.4 playbook文件的执行

[student@workstation deploy-playbook-test]$ ls ansible.cfg inventory user.yml [student@workstation deploy-playbook-test]$ ansible-playbook user.yml PLAY [新建一个用户] ************************************************************************************************************************************************ TASK [Gathering Facts] *************************************************************************************************************************************** ok: [servera] TASK [新建一个用户mmx] ********************************************************************************************************************************************* changed: [servera] PLAY RECAP *************************************************************************************************************************************************** servera : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 # 使用ansible ad hoc命令查看id=mmx的用户是否创建 [student@workstation deploy-playbook-test]$ ansible servera -a 'id mmx' servera | CHANGED | rc=0 >> uid=1200(mmx) gid=1200(mmx) groups=1200(mmx)

2.5 编写playbook练习

2.5.1 题目要求

进入playbook-basic目录 创建一个site.yml的playbook文件 作用在主机组web中 使用yum模块安装httpd服务 使用copy模块将files/index.html复制到/var/www/html/index.html 开启httpd服务,设为开机自启 检查playbook,运行playbook

2.5.2 实现准备操作

# 练习前准备 [student@workstation ~]$ lab playbook-basic start Setting up workstation for lab exercise work: · Verifying Ansible installation.............................. SUCCESS · Creating working directory.................................. SUCCESS · Deploying Ansible inventory................................. SUCCESS · Deploying ansible.cfg....................................... SUCCESS · Downloading index.html...................................... SUCCESS · Stop firewalld on serverc................................... SUCCESS · Stop firewalld on serverd................................... SUCCESS [student@workstation ~]$ ls deploy-adhoc deploy-manage deploy-playbook-test deploy-review playbook-basic [student@workstation ~]$ cd playbook-basic/ [student@workstation playbook-basic]$ ls ansible.cfg files inventory [student@workstation playbook-basic]$

2.5.3 编辑并运行ansible-playbook文件

# 编辑ansible-playbook文件 [student@workstation playbook-basic]$ cat site.yml --- - name: playbook test for site hosts: web tasks: - name: install server for web yum: name: httpd state: present - name: local files/index.html to /var/for web copy: src: files/index.html dest: /var/www/html/index.html - name: start the service and boot automatically service: name: httpd state: started enabled: true # 运行playbook文件(尝试运行),发现没问题 [student@workstation playbook-basic]$ ansible-playbook -C site.yml PLAY [playbook test for site] ************************************************************************************************************************************************************************************************ TASK [Gathering Facts] ******************************************************************************************************************************************************************************************************* ok: [serverc.lab.example.com] ok: [serverd.lab.example.com] TASK [install server for web] ************************************************************************************************************************************************************************************************ changed: [serverd.lab.example.com] changed: [serverc.lab.example.com] TASK [local files/index.html to /var/for web] ************************************************************************************************************************************************************ changed: [serverc.lab.example.com] changed: [serverd.lab.example.com] TASK [start the service and boot automatically] ************************************************************************************************************************************************************************ changed: [serverd.lab.example.com] changed: [serverc.lab.example.com] PLAY RECAP ******************************************************************************************************************************************************************************************************************* serverc.lab.example.com : ok=4 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 serverd.lab.example.com : ok=4 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 # 运行playbook文件 [student@workstation playbook-basic]$ ansible-playbook site.yml PLAY [playbook test for site] ************************************************************************************************************************************************************************************************ TASK [Gathering Facts] ******************************************************************************************************************************************************************************************************* ok: [serverc.lab.example.com] ok: [serverd.lab.example.com] TASK [install server for web] ************************************************************************************************************************************************************************************************ changed: [serverc.lab.example.com] changed: [serverd.lab.example.com] TASK [local files/index.html to /var/for web] ************************************************************************************************************************************************************ changed: [serverc.lab.example.com] changed: [serverd.lab.example.com] TASK [start the service and boot automatically] ************************************************************************************************************************************************************************ changed: [serverc.lab.example.com] changed: [serverd.lab.example.com] PLAY RECAP ******************************************************************************************************************************************************************************************************************* serverc.lab.example.com : ok=4 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 serverd.lab.example.com : ok=4 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

2.5.4 检查实验结果

# 使用curl命令检查web节点是否运行了配置了服务 [student@workstation playbook-basic]$ cat inventory [web] serverc.lab.example.com serverd.lab.example.com # 顺利读出数据 [student@workstation playbook-basic]$ curl serverc.lab.example.com This is a test page. [student@workstation playbook-basic]$ curl serverd.lab.example.com This is a test page.

2.5.5 结束实验

[student@workstation playbook-basic]$ lab playbook-basic finish Cleaning up exercise · Remove web content.......................................... SUCCESS · Remove package........................................ SUCCESS · Start firewalld on serverc.................................. SUCCESS · Start firewalld on serverd.................................. SUCCESS

3、 多playbook

3.1 在playbook里编写多个plays

[student@workstation deploy-playbook-test]$ cat multple.yml --- - name: first play hosts: homea tasks: - name: first task yum: name: httpd state: present - name: second task service: name: httpd enabled: true - name: first play hosts: home tasks: - name: first task yum: name: mariadb state: present

3.2 多playbook测试

[student@workstation deploy-playbook-test]$ ansible-playbook multple.yml PLAY [first play] ************************************************************************************************************************************************************************************************************ TASK [Gathering Facts] ******************************************************************************************************************************************************************************************************* ok: [servera] ok: [serverb] TASK [first task] ************************************************************************************************************************************************************************************************************ changed: [servera] changed: [serverb] TASK [second task] *********************************************************************************************************************************************************************************************************** changed: [serverb] changed: [servera] PLAY [first play] ************************************************************************************************************************************************************************************************************ TASK [Gathering Facts] ******************************************************************************************************************************************************************************************************* ok: [serverb] ok: [serverd] ok: [servera] ok: [serverc] TASK [first task] ************************************************************************************************************************************************************************************************************ changed: [serverb] changed: [servera] changed: [serverd] changed: [serverc] PLAY RECAP ******************************************************************************************************************************************************************************************************************* servera : ok=5 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 serverb : ok=5 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 serverc : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 serverd : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

3.3 提权属性

在playbook中,可以加入becom、becom_method等属性提升用户权限,完成更多操作 playbook中的提权语句优先级高于配置文件

参数 含义
remote_user: remoteuser 使用remoteuser用户
become: true 允许提权
become_method: sudo 提权方式sudo
become_user: XXX 提权至XXX用户

[student@workstation deploy-playbook-test]$ cat privilege.yml --- - name: 提升权限 hosts: home remote_user: student become: yes become_method: sudo become_user: root tasks: - name: 安装httpd服务 yum: name: httpd state: present

[student@workstation deploy-playbook-test]$ ansible-playbook privilege.yml PLAY [提升权限] ****************************************************************************************************************************************************************************************************************** TASK [Gathering Facts] ******************************************************************************************************************************************************************************************************* ok: [serverc] ok: [servera] ok: [serverd] ok: [serverb] TASK [安装************************************************************************************************************************************************************************************************************* changed: [serverb] changed: [serverd] changed: [serverc] changed: [servera] PLAY RECAP ******************************************************************************************************************************************************************************************************************* servera : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 serverb : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 serverc : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 serverd : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

4、 使用命令查看模块的使用

ansible模块众多,肯定是没办法都一一记住的,可以使用命令查找模块,在example中寻找相关用法

命令 作用
ansible-doc -l 列出所有已知模块
ansible-doc -l | grep 关键词 过滤关键词相关模块
ansible-doc 模块名 查询模块的使用方式
ansible-doc -s 模块名 简短列出模块的相关参数

4.1 使用ansible-doc -l

列出所有已知模块

[student@workstation deploy-playbook-test]$ ansible-doc -l a10_server Manage A10 Networks AX/SoftAX/Thunder/vThunder devices' server object a10_server_axapi3 Manage A10 Networks AX/SoftAX/Thunder/vThunder devices a10_service_group Manage A10 Networks AX/SoftAX/Thunder/vThunder devices' service groups a10_virtual_server Manage A10 Networks AX/SoftAX/Thunder/vThunder devices' virtual servers aci_aaa_user Manage AAA users (aaa:User) aci_aaa_user_certificate Manage AAA user certificates (aaa:UserCert) aci_access_port_block_to_access_port Manage port blocks of Fabric interface policy leaf profile interface selectors (infra:HPortS, infra:PortBlk) aci_access_port_to_interface_policy_leaf_profile Manage Fabric interface policy leaf profile interface selectors (infra:HPortS, infra:RsAccBaseGrp, infra:PortBlk) aci_access_sub_port_block_to_access_port Manage sub port blocks of Fabric interface policy leaf profile interface selectors (infra:HPortS, infra:SubPortBlk) aci_aep Manage attachable Access Entity Profile (AEP) objects (infra:AttEntityP, infra:ProvAcc) aci_aep_to_domain Bind AEPs to Physical or Virtual Domains (infra:RsDomP) aci_ap Manage top level Application Profile (AP) objects (fv:Ap) aci_bd Manage Bridge Domains (BD) objects (fv:BD) aci_bd_subnet Manage Subnets (fv:Subnet) aci_bd_to_l3out Bind Bridge Domain to L3 Out (fv:RsBDToOut) aci_config_rollback Provides rollback and rollback preview functionality (config:ImportP) ……

4.2 过滤出yum相关模块

[student@workstation deploy-playbook-test]$ ansible-doc -l | grep yum yum Manages packages with the `yum' package manager yum_repository Add or remove YUM repositories

4.3 查看yum模块的用途

[student@workstation deploy-playbook-test]$ ansible-doc yum > YUM (/usr/lib/python3.6/site-packages/ansible/modules/packaging/os/yum.py) Installs, upgrade, downgrades, removes, and lists packages and groups with the `yum' package manager. This module only works on Python 2. If you require Python 3 support see the [dnf] module. * This module is maintained by The Ansible Core Team * note: This module has a corresponding action plugin. OPTIONS (= is mandatory): - allow_downgrade Specify if the named package and version is allowed to downgrade a maybe already installed higher version of that package. Note that setting allow_downgrade=True can make this module behave in a non-idempotent way. The task could end up with a set of packages that does not match the complete list of specified packages to install (because dependencies between the downgraded package and others can cause changes to the packages which were in the earlier transaction). [Default: no] type: bool version_added: 2.4 - autoremove If `yes', removes all "leaf" packages from the system that were originally installed as dependencies of user-installed packages but which are no longer required by any such package. Should be used alone or when state is `absent' NOTE: This feature requires yum >= 3.4.3 (RHEL/CentOS 7+) [Default: no] type: bool version_added: 2.7 - bugfix If set to `yes', and `state=latest' then only installs updates that have been marked bugfix related. [Default: no] version_added: 2.6 - conf_file The remote yum configuration file to use for the transaction. [Default: (null)] version_added: 0.6 - disable_excludes Disable the excludes defined in YUM config files. If set to `all', disables all excludes. If set to `main', disable excludes defined in [main] in yum.conf. If set to `repoid', disable excludes defined for given repo id. [Default: (null)] version_added: 2.7 - disable_gpg_check Whether to disable the GPG checking of signatures of packages being installed. Has an effect only if state is `present' or `latest'. [Default: no] type: bool version_added: 1.2 - disable_plugin `Plugin' name to disable for the install/update operation. The disabled plugins will not persist beyond the transaction. [Default: (null)] version_added: 2.5 - disablerepo `Repoid' of repositories to disable for the install/update operation. These repos will not persist beyond the transaction. When specifying multiple repos, separate them with a `","'. As of Ansible 2.7, this can alternatively be a list instead of `","' separated string [Default: (null)] version_added: 0.9 - download_dir Specifies an alternate directory to store packages. Has an effect only if `download_only' is specified. [Default: (null)] type: str version_added: 2.8 - download_only Only download the packages, do not install them. [Default: no] type: bool version_added: 2.7 - enable_plugin `Plugin' name to enable for the install/update operation. The enabled plugin will not persist beyond the transaction. [Default: (null)] version_added: 2.5 - enablerepo `Repoid' of repositories to enable for the install/update operation. These repos will not persist beyond the transaction. When specifying multiple repos, separate them with a `","'. As of Ansible 2.7, this can alternatively be a list instead of `","' separated string [Default: (null)] version_added: 0.9 - exclude Package name(s) to exclude when state=present, or latest [Default: (null)] version_added: 2.0 - install_weak_deps Will also install all packages linked by a weak dependency relation. NOTE: This feature requires yum >= 4 (RHEL/CentOS 8+) [Default: yes] type: bool version_added: 2.8 - installroot Specifies an alternative installroot, relative to which all packages will be installed. [Default: /] version_added: 2.3 - list Package name to run the equivalent of yum list against. In addition to listing packages, use can also list the following: `installed', `updates', `available' and `repos'. [Default: (null)] - lock_timeout Amount of time to wait for the yum lockfile to be freed. [Default: 0] type: int version_added: 2.8 - name A package name or package specifier with version, like `name-1.0'. If a previous version is specified, the task also needs to turn `allow_downgrade' on. See the `allow_downgrade' documentation for caveats with downgrading packages. When using state=latest, this can be `'*'' which means run `yum -y update'. You can also pass a url or a local path to a rpm file (using state=present). To operate on several packages this can accept a comma separated string of packages or (as of 2.0) a list of packages. (Aliases: pkg)[Default: (null)] - releasever Specifies an alternative release from which all packages will be installed. [Default: (null)] version_added: 2.7 - security If set to `yes', and `state=latest' then only installs updates that have been marked security related. [Default: no] type: bool version_added: 2.4 - skip_broken Skip packages with broken dependencies(devsolve) and are causing problems. [Default: no] type: bool version_added: 2.3 - state Whether to install (`present' or `installed', `latest'), or remove (`absent' or `removed') a package. `present' and `installed' will simply ensure that a desired package is installed. `latest' will update the specified package if it's not of the latest available version. `absent' and `removed' will remove the specified package. Default is `None', however in effect the default action is `present' unless the `autoremove' option is¬ enabled for this module, then `absent' is inferred. (Choices: absent, installed, latest, present, removed)[Default: (null)] - update_cache Force yum to check if cache is out of date and redownload if needed. Has an effect only if state is `present' or `latest'. (Aliases: expire-cache)[Default: no] type: bool version_added: 1.9 - update_only When using latest, only update installed packages. Do not install packages. Has an effect only if state is `latest' [Default: no] type: bool version_added: 2.5 - use_backend This module supports `yum' (as it always has), this is known as `yum3'/`YUM3'/`yum-deprecated' by upstream yum developers. As of Ansible 2.7+, this module also supports `YUM4', which is the "new yum" and it has an `dnf' backend. By default, this module will select the backend based on the `ansible_pkg_mgr' fact. (Choices: auto, yum, yum4, dnf)[Default: auto] version_added: 2.7 - validate_certs This only applies if using a url as the source of the rpm. e.g. for localinstall. If set to `no', the SSL certificates will not be validated. This should only set to `no' used on personally controlled sites using self-signed certificates as it avoids verifying the source site. Prior to 2.1 the code worked as if this was set to `yes'. [Default: yes] type: bool version_added: 2.1 NOTES: * When used with a `loop:` each package will be processed individually, it is much more efficient to pass the list directly to the `name` option. * In versions prior to 1.9.2 this module installed and removed each package given to the yum module separately. This caused problems when packages specified by filename or url had to be installed or removed together. In 1.9.2 this was fixed so that packages are installed in one yum transaction. However, if one of the packages adds a new yum repository that the other packages come from (such as epel-release) then that package needs to be installed in a separate task. This mimics yum's command line behaviour. * Yum itself has two types of groups. "Package groups" are specified in the rpm itself while "environment groups" are specified in a separate file (usually by the distribution). Unfortunately, this division becomes apparent to ansible users because ansible needs to operate on the group of packages in a single transaction and yum requires groups to be specified in different ways when used in that way. Package groups are specified as "@development-tools" and environment groups are "@^gnome-desktop-environment". Use the "yum group list hidden ids" command to see which category of group the group you want to install falls into. * The yum module does not support clearing yum cache in an idempotent way, so it was decided not to implement it, the only method is to use shell and call the yum command directly, namely "shell: yum clean all" https://github.com/ansible/ansible/pull/31450#issuecomment-352889579 REQUIREMENTS: yum AUTHOR: Ansible Core Team, Seth Vidal (@skvidal), Eduard Snesarev (@verm666), Berend De Schouwer (@berenddeschouwer), Abhijeet Kasurde (@Akasurde), Adam Miller (@maxamillion) METADATA: status: - stableinterface supported_by: core EXAMPLES: - name: install the latest version of Apache yum: name: httpd state: latest - name: ensure a list of packages installed yum: name: "{{ packages }}" vars: packages: - httpd - httpd-tools - name: remove the Apache package yum: name: httpd state: absent - name: install the latest version of Apache from the testing repo yum: name: httpd enablerepo: testing state: present - name: install one specific version of Apache yum: name: httpd-2.2.29-1.4.amzn1 state: present - name: upgrade all packages yum: name: '*' state: latest - name: upgrade all packages, excluding kernel & foo related packages yum: name: '*' state: latest exclude: kernel*,foo* - name: install the nginx rpm from a remote repo yum: name: http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state: present - name: install nginx rpm from a local file yum: name: /usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm state: present - name: install the 'Development tools' package group yum: name: "@Development tools" state: present - name: install the 'Gnome desktop' environment group yum: name: "@^gnome-desktop-environment" state: present - name: List ansible packages and register result to print with debug later. yum: list: ansible register: result - name: Install package with multiple repos enabled yum: name: sos enablerepo: "epel,ol7_latest" - name: Install package with multiple repos disabled yum: name: sos disablerepo: "epel,ol7_latest" - name: Install a list of packages yum: name: - nginx - postgresql - postgresql-server state: present - name: Download the nginx package but do not install it yum: name: - nginx state: latest download_only: true

4.4 简短列出yum模块

[student@workstation deploy-playbook-test]$ ansible-doc yum -s - name: Manages packages with the `yum' package manager yum: allow_downgrade: # Specify if the named package and version is allowed to downgrade a maybe already installed higher version of that package. Note that setting allow_downgrade=True can make this module behave in a non-idempotent way. The task could end up with a set of packages that does not match the complete list of specified packages to install (because dependencies between the downgraded package and others can cause changes to the packages which were in the earlier transaction). autoremove: # If `yes', removes all "leaf" packages from the system that were originally installed as dependencies of user-installed packages but which are no longer required by any such package. Should be used alone or when state is `absent' NOTE: This feature requires yum >= 3.4.3 (RHEL/CentOS 7+) bugfix: # If set to `yes', and `state=latest' then only installs updates that have been marked bugfix related. conf_file: # The remote yum configuration file to use for the transaction. disable_excludes: # Disable the excludes defined in YUM config files. If set to `all', disables all excludes. If set to `main', disable excludes defined in [main] in yum.conf. If set to `repoid', disable excludes defined for given repo id. disable_gpg_check: # Whether to disable the GPG checking of signatures of packages being installed. Has an effect only if state is `present' or `latest'. disable_plugin: # `Plugin' name to disable for the install/update operation. The disabled plugins will not persist beyond the transaction. disablerepo: # `Repoid' of repositories to disable for the install/update operation. These repos will not persist beyond the transaction. When specifying multiple repos, separate them with a `","'. As of Ansible 2.7, this can alternatively be a list instead of `","' separated string download_dir: # Specifies an alternate directory to store packages. Has an effect only if `download_only' is specified. download_only: # Only download the packages, do not install them. enable_plugin: # `Plugin' name to enable for the install/update operation. The enabled plugin will not persist beyond the transaction. enablerepo: # `Repoid' of repositories to enable for the install/update operation. These repos will not persist beyond the transaction. When specifying multiple repos, separate them with a `","'. As of Ansible 2.7, this can alternatively be a list instead of `","' separated string exclude: # Package name(s) to exclude when state=present, or latest install_weak_deps: # Will also install all packages linked by a weak dependency relation. NOTE: This feature requires yum >= 4 (RHEL/CentOS 8+) installroot: # Specifies an alternative installroot, relative to which all packages will be installed. list: # Package name to run the equivalent of yum list against. In addition to listing packages, use can also list the following: `installed', `updates', `available' and `repos'. lock_timeout: # Amount of time to wait for the yum lockfile to be freed. name: # A package name or package specifier with version, like `name-1.0'. If a previous version is specified, the task also needs to turn `allow_downgrade' on. See the `allow_downgrade' documentation for caveats with downgrading packages. When using state=latest, this can be `'*'' which means run `yum -y update'. You can also pass a url or a local path to a rpm file (using state=present). To operate on several packages this can accept a comma separated string of packages or (as of 2.0) a list of packages. releasever: # Specifies an alternative release from which all packages will be installed. security: # If set to `yes', and `state=latest' then only installs updates that have been marked security related. skip_broken: # Skip packages with broken dependencies(devsolve) and are causing problems. state: # Whether to install (`present' or `installed', `latest'), or remove (`absent' or `removed') a package. `present' and `installed' will simply ensure that a desired package is installed. `latest' will update the specified package if it's not of the latest available version. `absent' and `removed' will remove the specified package. Default is `None', however in effect the default action is `present' unless the `autoremove' option is¬ enabled for this module, then `absent' is inferred. update_cache: # Force yum to check if cache is out of date and redownload if needed. Has an effect only if state is `present' or `latest'. update_only: # When using latest, only update installed packages. Do not install packages. Has an effect only if state is `latest' use_backend: # This module supports `yum' (as it always has), this is known as `yum3'/`YUM3'/`yum-deprecated' by upstream yum developers. As of Ansible 2.7+, this module also supports `YUM4', which is the "new yum" and it has an `dnf' backend. By default, this module will select the backend based on the `ansible_pkg_mgr' fact. validate_certs: # This only applies if using a url as the source of the rpm. e.g. for localinstall. If set to `no', the SSL certificates will not be validated. This should only set to `no' used on personally controlled sites using self-signed certificates as it avoids verifying the source site. Prior to 2.1 the code worked as if this was set to `yes'.

5、 模块的状态、维护团队

在文档中有如下说明,列举了模块的状态已经开发团队

REQUIREMENTS: yum AUTHOR: Ansible Core Team, Seth Vidal (@skvidal), Eduard Snesarev (@verm666), Berend De Schouwer (@berenddeschouwer), Abhijeet Kasurde (@Akasurde), Adam Miller (@maxamillion) METADATA: status: - stableinterface supported_by: core

5.1 状态说明

状态值 说明
stableinterface 很稳定
preview 不稳定
deprecated 可能会淘汰(新的模块替代)
removed 已移除

5.2 维护团队说明

团队名称 说明
core 核心团队(红帽)
curated 企业开发
community 社区

6、yaml文件的语法

6.1 可以使用#做注释

[student@workstation deploy-playbook-test]$ cat test.yml --- # 这是一个注释 - name: 新建一个用户 hosts: servera tasks: - name: 新建一个用户mmx user: name: mmx uid: 1200 state: absent

6.2、 可以使用 | 或者> 连接字符串

符合 含义
| 每一行结尾使用\n
> 每一个回车当成一个空格

# 使用 | 效果 [student@workstation deploy-playbook-test]$ cat user.yml --- - name: | hello my name mmx hosts: servera tasks: - name: 新建一个用户mmx user: name: mmx uid: 1200 state: absent [student@workstation deploy-playbook-test]$ ansible-playbook -C user.yml PLAY [hello my name mmx] ***************************************************************************************************************************************************************************************************** TASK [Gathering Facts] ******************************************************************************************************************************************************************************************************* ok: [servera] TASK [新建一个用户mmx] ************************************************************************************************************************************************************************************************************* ok: [servera] PLAY RECAP ******************************************************************************************************************************************************************************************************************* servera : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 # 使用 > 效果 [student@workstation deploy-playbook-test]$ cat user.yml --- - name: > hello my name mmx hosts: servera tasks: - name: 新建一个用户mmx user: name: mmx uid: 1200 state: absent [student@workstation deploy-playbook-test]$ ansible-playbook -C user.yml PLAY [hello my name mmx] ***************************************************************************************************************************************************************************************************** TASK [Gathering Facts] ******************************************************************************************************************************************************************************************************* ok: [servera] TASK [新建一个用户mmx] ************************************************************************************************************************************************************************************************************* ok: [servera] PLAY RECAP ******************************************************************************************************************************************************************************************************************* servera : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

6.3 清单文件写法

6.3.1 每行一个元素(推荐)

[student@workstation deploy-playbook-test]$ cat user.yml --- - name: remove user hosts: - servera - serverb tasks: - name: 新建一个用户mmx user: name: mmx uid: 1200 state: absent

6.3.2 每行多个元素(不推荐)

[student@workstation deploy-playbook-test]$ cat user.yml --- - name: remove user hosts: servera,serverb tasks: - name: 新建一个用户mmx user: {name: mmx, uid: 1200, state: absent}

7、 多plays练习

7.1 题目要求

开启实验lab:lab playbook-multi start 进入playbook-multi目录,创建yml文件intranet.yml 受管主机servera.lab.example.com,并允许提权 使用yum模块安装软件httpd和firewalld 在web服务器中添加一段内容“Wecome to the example.com intranet!\n" 防火墙开启httpd服务,激活并开机运行 开启httpd服务 定义主机组localhost的tasks任务 不需要提升权限 localhost下使用uri模块,访问http://servera.lab.example.com,返回结果为200 允许playbook,检查结果

7.2 开启实验,编写yml文件

[student@workstation ~]$ lab playbook-multi start Setting up workstation for lab exercise work: · Verifying Ansible installation.............................. SUCCESS · Creating working directory.................................. SUCCESS · Deploying Ansible inventory................................. SUCCESS · Deploying ansible.cfg....................................... SUCCESS [student@workstation ~]$ ls deploy-adhoc deploy-manage deploy-playbook-test deploy-review playbook-basic playbook-multi [student@workstation ~]$ cd playbook-multi/ [student@workstation playbook-multi]$ ls ansible.cfg inventory [student@workstation playbook-multi]$ cat * [defaults] inventory=inventory remote_user=devops [privilege_escalation] become=False become_method=sudo become_user=root become_ask_pass=False servera.lab.example.com

[student@workstation playbook-multi]$ cat intranet.yml --- - name: Enable intranet services hosts: servera.lab.example.com becom: yes tasks: - name: install and firewalld yum: name: - httpd - firewalld state: latest - name: Wecome to the example.com intranet!\n for server copy: content: "Wecome to the example.com intranet!\n" dest: /var/www/html/index.html - name: allow service firewalld: service: http permanent: yes immediate: yes state: enabled - name: start service service: name: httpd state: started enabled: yes - name: set localhost hosts: localhost becom: no tasks: - name: use uri module access servera uri: url: http://servera.lab.example.com return_content: yes status_code: 200

7.3 检查练习结果

[student@workstation playbook-multi]$ ansible-playbook intranet.yml PLAY [Enable intranet services] ********************************************************************************************************************************************************************************************** TASK [Gathering Facts] ******************************************************************************************************************************************************************************************************* ok: [servera.lab.example.com] TASK [install and firewalld] ******************************************************************************************************************************************************************************************* changed: [servera.lab.example.com] TASK [Wecome to the example.com intranet!\n for server] **************************************************************************************************************************************************************** changed: [servera.lab.example.com] TASK [allow service] **************************************************************************************************************************************************************************************************** changed: [servera.lab.example.com] TASK [start service] **************************************************************************************************************************************************************************************************** changed: [servera.lab.example.com] PLAY [set localhost] ********************************************************************************************************************************************************************************************************* TASK [Gathering Facts] ******************************************************************************************************************************************************************************************************* ok: [localhost] TASK [use uri module access servera] ***************************************************************************************************************************************************************************************** ok: [localhost] PLAY RECAP ******************************************************************************************************************************************************************************************************************* localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 servera.lab.example.com : ok=5 changed=4 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 # 使用-v参数截取部分,发现显示 "content": "Wecome to the example.com intranet!\n",实验成功 [student@workstation playbook-multi]$ ansible-playbook intranet.yml -v TASK [use uri module access servera] ***************************************************************************************************************************************************************************************** ok: [localhost] => {"accept_ranges": "bytes", "changed": false, "connection": "close", "content": "Wecome to the example.com intranet!\n", "content_length": "36", "content_type": "text/html; charset=UTF-8", "cookies": {}, "cookies_string": "", "date": "Wed, 03 Aug 2022 09:00:41 GMT", "elapsed": 0, "etag": "\"24-5e5527659ed62\"", "last_modified": "Wed, 03 Aug 2022 09:00:19 GMT", "msg": "OK (36 bytes)", "redirected": false, "server": "Apache/2.4.37 (Red Hat Enterprise Linux)", "status": 200, "url": "http://servera.lab.example.com"} # 实验结束 [student@workstation ~]$ lab playbook-multi finish Cleaning up exercise: · Remove firewall configuration............................... SUCCESS · Remove web content.......................................... SUCCESS · Remove package........................................ SUCCESS

8、 综合实验

8.1 题目要求

开启实验环境lab playbook-review start 创建一个新的playbook,名为XXX/internet.yml,name描述为:Enable internet service,在受管节点serverb.lab.exmaple.com下运行,需要使用become提升权限。 使用yum模块安装软件包:firewalld、httpd、mariadb-server、php和php-mysqlnd 使用firewalld模块,开启firewalld服务,放行httpd服务 使用service模块,让httpd和mariadb服务启动并开机自动运行 使用get_url模块从-到 /var/www/html/ 新的一个任务,在受管节点localhost下,不用权限提升 使用uri模块,访问serverb.lab.example.com,返回状态值为200 检查并运行playbook 判断成绩,并结束实验

8.2 编写playbook文件

[student@workstation playbook-review]$ cat internet.yml --- - name: Enable internet services hosts: serverb.lab.example.com become: yes tasks: - name: install firewalld mariadb-server php and php-mysqlnd packages yum: name: - firewalld - httpd - mariadb-server - php - php-mysqlnd state: latest - name: allow server for httpd firewalld: service: http permanent: yes immediate: yes state: enabled - name: start service and mariadb service: name: httpd state: started enabled: true - name: start service and mariadb service: name: mariadb state: started enabled: true - name: set web server index.html get_url: url: http://materials.example.com/labs/playbook-review/index.php dest: /var/www/html/ - name: access web server hosts: localhost become: no tasks: - name: check web server and return status code of 200 uri: url: http://serverb.lab.example.com return_content: yes status_code: 200

8.3 运行playbook

[student@workstation playbook-review]$ ansible-playbook internet.yml PLAY [Enable internet services] ********************************************************************************************************************************************************************************************** TASK [Gathering Facts] ******************************************************************************************************************************************************************************************************* ok: [serverb.lab.example.com] TASK [install firewalld mariadb-server php and php-mysqlnd packages] *************************************************************************************************************************************************** changed: [serverb.lab.example.com] TASK [allow server for ************************************************************************************************************************************************************************************************ changed: [serverb.lab.example.com] TASK [start service and mariadb] *************************************************************************************************************************************************************************************** changed: [serverb.lab.example.com] TASK [start service and mariadb] *************************************************************************************************************************************************************************************** changed: [serverb.lab.example.com] TASK [set web server index.html] ********************************************************************************************************************************************************************************************* changed: [serverb.lab.example.com] PLAY [access web server] ***************************************************************************************************************************************************************************************************** TASK [Gathering Facts] ******************************************************************************************************************************************************************************************************* ok: [localhost] TASK [check web server and return status code of 200] ************************************************************************************************************************************************************************ changed: [localhost] PLAY RECAP ******************************************************************************************************************************************************************************************************************* localhost : ok=1 changed=5 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 serverb.lab.example.com : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 # 判断成绩 [student@workstation playbook-review]$ lab playbook-review grade Grading the student's work on serverb: · Verify package installation........................... PASS · Verify firewalld package installation....................... PASS · Verify mariadb-server package installation.................. PASS · Verify php package installation............................. PASS · Verify php-mysqlnd package installation..................... PASS · Verify service........................................ PASS · Verify firewalld service.................................... PASS · Verify mariadb service...................................... PASS · Verify firewalld configuration.............................. PASS · Verify web site............................................. PASS Overall lab grade.............................................. PASS # 结束实验 [student@workstation playbook-review]$ lab playbook-review finish Cleaning up the lab on serverb: Cleanup · Remove firewall configuration............................... SUCCESS · Remove web content.......................................... SUCCESS · Remove package........................................ SUCCESS · Remove mariabdb-server package.............................. SUCCESS · Remove php package.......................................... SUCCESS · Remove php-mysqlnd package.................................. SUCCESS

9、 小结

如何编写playbook文件 playbook运行单tasks和多tasks的方式 如何查询ansible的文档 ansible-playbook的语法规范

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:“玲珑杯”ACM比赛 Round #13
下一篇:一次 sql 优化经历,太有趣了!(一次就怀孕的几率大吗)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~