【Ansible】Playbook实例

Learn to build Ansible playbooks with our guide, one step at a time

In our previous posts, we introduced Ansible fundamentals, and dove deeper into Ansible playbooks. Now let’s learn to create an Ansible playbook step by step. Working with a playbook, we’ll go from deploying a simple HTML website to a complete LAMP stack.

Deploying Simple HTML Page

To deploy a simple HTML page, we need to ensure that apache is installed and configured on our host machine. So therefore, in this section we will:

  • install Apache
  • start the Apache service
  • deploy a static webpage with images – This static webpage will leverage Ansible templates where it will display the text “Thank you for reading this post. My IP Address is <ip-address-of-instance>” and cloudacademy logo. To fetch the IP address of host, it will rely on Ansible Fact
  • restart Apache once the deployment is over

Before we move forward, let’s have a look at the high-level structure of this simple Ansible playbook.

1

2

3

4

5

6

7

8

9

10

11

12

site.yml – starting point of our ansible playbook

hosts – carrying hosts information

roles/ - defining what each type of server has to perform

webservers/

tasks/ - tasks performed on webservers

main.yml

handlers/ - running tasks under particular events

main.yml

templates/ - configuration files which can reference variables

index.html.j2

files/ - files to be copied to webservers

cloud.png

Lets go through the configuration file line by line and see how configuration works.

hosts – points to Ansible hosts. Here’s a possible syntax:

1

2

[webservers]

10.0.0.156

site.yml – the starting point for executing our Ansible playbook. Includes information about hosts and roles associated with them.

1

2

3

4

5

6

7

---

- name: install and configure webservers

hosts: webservers

remote_user: ec2-user

sudo: yes

roles:

- webservers

If we want to log into our host machines using a different username and with sudo privileges, we need to use the “remote_user” and “sudo: yes” parameter in our site.yml file. There can be additional parameters too, but they’re not needed right now. Here, we have also defined roles granted to hosts in the [webservers] group.

main.yml (Tasks) – This configuration file defines tasks to be executed on hosts that have webservers roles granted. It looks like:

1

2

3

4

5

6

7

8

9

10

11

---

# This task installs and enables apache on webservers

- name: ensure apache is installed

yum: pkg=httpd state=latest

- name: ensure apache is running

service: name=httpd state=running enabled=yes

- name: copy files to document root

copy: src=cloud.png dest=/var/www/html/cloud.png

- name: copy application code to document root

template: src=index.html.j2 dest=/var/www/html/index.html

notify: restart apache

Since YAML files are so intuitive, we can easily see that this will install and run Apache on host instances and copy certain files and templates to the host’s document root.

main.yml (handlers) – This configuration file defines the action to be performed only upon notification of tasks or state changes. In main.yml (tasks), we defined notify: restart apache handler which will restart Apache once the files and templates are copied to hosts.

1

2

3

---

- name: restart apache

service: name=httpd state=restarted

index.html.j2 (template) – a file you can deploy on hosts. However, template files also include some reference variables which are pulled from variables defined as part of an Ansible playbook or facts gathered from the hosts. Our index.html.j2 file looks like a regular html webpage with a referenced variable.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<html>

<head>

<title>CloudAcademy Ansible Demo</title>

</head>

<body>

<h1>

Thank you for reading this post.

My IP Address is {{ ansible_eth0.ipv4.address }}

</h1>

<br/><br/><br/>

<p>

<img src="cloud.png" alt="CloudAcademy Logo"/>

</p>

</body>

</html>

We have declared a reference variable “{{ ansible_eth0.ipv4.address }}” which will print the IP address of the host on which this Ansible playbook is executed.

cloud.png (files) – The regular image file to be copied to hosts.

Once we have all the files created and present, we can execute an ansible-playbook command and configure our hosts.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

build# ansible-playbook site.yml -i hosts

PLAY [install and configure webservers] ***************************************

GATHERING FACTS ***************************************************************

ok: [10.0.0.156]

TASK: [webservers | ensure apache is installed] *******************************

changed: [10.0.0.156]

TASK: [webservers | ensure apache is running] *********************************

changed: [10.0.0.156]

TASK: [webservers | copy files to document root] ******************************

changed: [10.0.0.156]

TASK: [webservers | copy application code to document root] *******************

changed: [10.0.0.156]

NOTIFIED: [webservers | restart apache] ***************************************

changed: [10.0.0.156]

PLAY RECAP ********************************************************************

10.0.0.156                 : ok=6   changed=5   unreachable=0   failed=0

That’s it. We have installed Apache and deployed our webpage using host-based files. On browsing our host’s IP address, we will see our static webpage with the referenced variables value defined.

Deploying a PHP webpage configured to work with a MySQL database

So until now, we’ve installed and started Apache, deployed a static webpage, and restarted Apache using handlers. Now we will upgrade the functionality of our existing Ansible playbook by adding additional features. Specifically, we’ll:

  • install php and related packages
  • install mysql server
  • create databases in mysql server
  • grant privileges to databases
  • deploy a php web page which will list the names of all the databases in our mysql server and print certain facts about our host.

This will modify the structure our existing Ansible playbook:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

site.yml – starting point of our ansible playbook

hosts – carrying hosts information

group_vars

all – carrying variables for groups

roles/ - defining what each type of server has to perform

webservers/

tasks/ - tasks performed on webservers

main.yml

handlers/ - running tasks under particular events

main.yml

templates/ - configuration files which can reference variables

index.php.j2

files/ - files to be copied to webservers

cloud.png

dbservers

tasks/

main.yml

all (group_vars) : contains group-specific variables. Currently, we have only one group i.e., all.

1

2

dbuser: ansible

dbpassword: 12345

hosts : We have to update our hosts file if the webserver and database server are configured on the same host.

1

2

[all]

10.0.0.156

site.yml : Once we have updated our hosts file with a new group “all”, we have to update our site.yml file which will grant the webserver and dbserver role to the “all” host group.

1

2

3

4

5

6

7

8

---

- name: install and configure webservers

hosts: all

remote_user: ec2-user

sudo: yes

roles:

- webservers

- dbservers

main.yml (tasks for webservers) : This YAML file will now install additional php related packages.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

---

# These task installs and enables apache on webservers

- name: ensure apache,php related packages are installed

yum: name={{ item }} state=present

with_items:

- httpd

- php

- php-mysql

- name: ensure apache is running

service: name=httpd state=running enabled=yes

- name: copy files to document root

copy: src=cloud.png dest=/var/www/html/cloud.png

- name: copy application code to document root

template: src=index.php.j2 dest=/var/www/html/index.php

notify: restart apache

index.php.j2 (templates) : Instead of an html file, we’ve moved to index.php which includes application code to print names of all databases and other operating system related information:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

<html>

<head>

<title>CloudAcademy Ansible Demo</title>

</head>

<body>

<h3>

Thank you for reading this post. My IP Address is {{ ansible_eth0.ipv4.address }}.

This is {{ ansible_system }} OS with {{ ansible_userspace_architecture }} architecture

</h3>

<p>

<strong>List of Databases:</strong> <br/>

<?php

//Spoiler: don‘t do this at home!

$dbobj = mysql_connect(‘{{ ansible_lo.ipv4.address }}‘, ‘{{ dbuser }}‘, ‘{{ dbpassword }}‘);

if (!$dbobj) { die(‘Could not connect: ‘ . mysql_error()); }

$result = mysql_query("SHOW DATABASES");

while ($res = mysql_fetch_assoc($result)){

echo $res[‘Database‘] . "<br/>";

}

?>

</p>

<br/>

<p><img src="cloud.png" alt="CloudAcademy Logo"></p>

</body>

</html>

main.yml (tasks for dbservers) : This configuration file will install the mysql-server, and mysql python packages, create databases, and create database users.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

---

# These task installs and enables apache on webservers

- name: ensure mysql is installed

yum: name={{ item }} state=present

with_items:

- mysql-server

- MySQL-python

- name: ensure mysql is running

service: name=mysqld state=running enabled=yes

- name: create application database

mysql_db: name={{ item }} state=present

with_items:

- ansible_db01

- ansible_db02

- name: create application user

mysql_user: name={{ dbuser }} password={{ dbpassword }} priv=*.*:ALL state=present

That’s it. Our Ansible playbook to deploy a LAMP stack is now ready. We built up a playbook that will install Apache, php, mysql-server, create a mysql user and databases and deploy our application code which prints information about Ansible’s host and list of databases.

To execute this Ansible playbook on host, we will use the ansible-playbook command:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

#ansible-playbook site.yml -i hosts

PLAY [install and configure webservers] ***************************************

GATHERING FACTS ***************************************************************

ok: [10.0.0.156]

TASK: [webservers | ensure apache,php related packages are installed] *********

changed: [10.0.0.156] => (item=httpd,php,php-mysql)

TASK: [webservers | ensure apache is running] *********************************

changed: [10.0.0.156]

TASK: [webservers | copy files to document root] ******************************

changed: [10.0.0.156]

TASK: [webservers | copy application code to document root] *******************

changed: [10.0.0.156]

TASK: [dbservers | ensure mysql is installed] *********************************

changed: [10.0.0.156] => (item=mysql-server,MySQL-python)

TASK: [dbservers | ensure mysql is running] ***********************************

changed: [10.0.0.156]

TASK: [dbservers | create application database] *******************************

changed: [10.0.0.156] => (item=ansible_db01)

changed: [10.0.0.156] => (item=ansible_db02)

TASK: [dbservers | create application user] ***********************************

changed: [10.0.0.156]

NOTIFIED: [webservers | restart apache] ***************************************

changed: [10.0.0.156]

PLAY RECAP *******************************************************************

10.0.0.156                 : ok=10   changed=9   unreachable=0   failed=0

Browsing to our host IP address will display:

There’s lots more to learn about Ansible in future posts!

参考资料:https://cloudacademy.com/blog/building-ansible-playbooks-step-by-step/

时间: 2024-08-29 00:18:16

【Ansible】Playbook实例的相关文章

Python+Django+Ansible Playbook自动化运维项目实战

Python+Django+Ansible Playbook自动化运维项目实战网盘地址:https://pan.baidu.com/s/1bZ1Ju0mld3KLZawdxZ7m6Q 密码: 5k9x备用地址(腾讯微云):https://share.weiyun.com/5E7aUWv 密码:wzfdrn 本课程将带你从项目实践角度出发,围绕自动化资产扫描和发现.Ansible自动化任务执行的内容展开,让运维更简单.更高效,Hold住高薪! 适合人群:如果你是一位运维党,对Python运维自动化

Ansible PlayBook语法(4)

title: Ansible PlayBook语法(4) date: 2018-12-02 10:53:24 tags: Ansible categories: Ansible copyright: true --- Ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具(puppet.cfengine.chef.func.fabric)的优点,实现了批量系统配置.批量程序部署.批量运行命令等功能,ansible是基于模块工作的,本身没有批量部署的能力,真正具有批量部署

运维自动化之ansible playbook一键化解决大量主机bash更新问题

今天发现有bash漏洞,但我这里近1000台服务器,为了方便.省时间,觉得使用ansible安装bash更新包,下面分享一下我的安装方法. 1.安装的playbook的内容 19:00:03 # cd /etc/ansible [email protected]:/etc/ansible 19:00:06 # cat update_bash.yml  --- - hosts: "{{ host }}"   remote_user: "{{ user }}"   ga

ansible playbook yummodule error

ansible playbookweb.yaml[[email protected] Desktop]# cat web.yaml- name: web servers  remote_user: root  hosts: webservers tasks:  - name: install httpd    yum: name=httpd state=present  - name: httpd service     service: name=httpd enabled=yes state

运维自动化之ansible playbook安装mysql

上次介绍了如何使用ansible playbook安装zabbix客户端(http://dl528888.blog.51cto.com/2382721/1436745),这次介绍一下如何使用playbook安装mysql. 下面是安装mysql的信息: mysql_basedir: /data/mysql/basedir                    源码目录 mysql_datadir: /data/mysql/datadir                    数据目录 mysql

Ansible playbook API 开发 调用测试

Ansible是Agentless的轻量级批量配置管理工具,由于出现的比较晚(13年)基于Ansible进行开发的相关文档较少,因此,这里通过一些小的实验,结合现有资料以及源码,探索一下Ansible的二次开发. 随笔的内容分为三个部分 playbook编辑执行 python 调用API执行playbook java调用python程序进行playbook的执行 实验的环境是centos6,ansible版本是1.9.4,python版本是2.6.6,jdk版本是1.7U79 一.playboo

运维自动化之ansible playbook安装ruby环境

本来不想打算写安装ruby的,但看几个puppet的群里有人对安装ruby比较茫然,所以这里简单介绍一下如何安装ruby. ps:话说现在也就gitlab.capistrano.puppet等软件使用ruby,最新2010年的软件好的都是python了,比如ansible.salt等. 下面是安装ruby的信息: ruby_version: 1.9.3 ruby_dir: /usr/local gem_version: 1.8.23 bundle_version: 1.6.3 可以看到ruby的

Ansible Playbook - Understanding YAML

要想用Ansible操作复杂的任务,就必须要学会YAML语法的书写,不光是Ansible,连他的竞争对手saltstack也使用了YAML,下面来学习一下YAML语法的格式,省得到要你写个Playbook的时候手忙脚乱的要好. 引用一下维基:YAML是"YAML Ain't a Markup Language"(YAML不是一种标记语言)的递回缩写.在开发的这种语言时,YAML 的意思其实是:"Yet Another Markup Language"(仍是一种标记语

自动化运维工具ansible playbook和roles的使用

ansible的结构: Inventory 用来定义被控制端 Modules 定义被控制端可用的操作 Ad Hoc Commands 定义被控制端可以执行命令的 Playbook 批量运行的方式 Tasks: 任务:由各模块所支持执行的特定操作:可以通过ansible-doc module_name来查看帮助文档,非常详细 -m  user -a 'name= password=' Variables: 变量 Templates: 模板:(如执行httpd服务时,各节点上httpd的配置文件内容