Ansible简介

Contents

Ansible

1
2
3
apt update

apt install -y ansible
1
2
3
4
5
6
7
8
vim ~/.ansible.cfg
# [defaults]
# host_key_checking = False

ls ~/.ssh/
# id_rsa id_rsa.pub known_hosts
ssh -T -p 10133 op@120.55.98.237
ssh -T -p 10133 op@115.29.164.63

Inventory

1
2
3
4
vim hosts
# [test]
# test1 ansible_ssh_host=120.55.98.237 ansible_ssh_port=10133 ansible_ssh_user=op
# test2 ansible_ssh_host=115.29.164.63 ansible_ssh_port=10133 ansible_ssh_user=op

Command

1
2
3
4
5
6
7
8
9
ansible -i hosts test1 -m command -a 'echo Hello World.'
# test1 | SUCCESS | rc=0 >>
# Hello World.

ansible -i hosts test -m command -a 'echo Hello World.'
# test1 | SUCCESS | rc=0 >>
# Hello World.
# test2 | SUCCESS | rc=0 >>
# Hello World.

Script

1
2
3
mkdir sites

vim sites/main.py
1
2
3
4
5
6
7
#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import os

cmd = 'find /opt/sites -maxdepth 1 -type d'
os.system(cmd)
1
ansible -i hosts test -m script -a sites/main.py

Playbook

1
2
3
mkdir sites

vim sites/main.yml
1
2
3
4
5
6
7
8
9
10
11
12
---

- name: scan sites
hosts: all
remote_user: op
tasks:
- name: scan sites
script: main.py
register: result
- name: print stdout
debug:
msg: '{{ result.stdout }}'
1
ansible-playbook -i hosts sites/main.yml

Flask

1
2
3
pipenv --python 3.7

pipenv install flask

关于pipenv更多介绍 可以参考pipenv

1
vim app.py
1
2
3
4
5
6
7
8
9
10
11
from flask import Flask
import subprocess

app = Flask(__name__)


@app.route('/sites')
def index():
cmd = 'ansible-playbook -i hosts sites/main.yml'
ret = subprocess.check_output(cmd, shell=True)
return ret
1
2
3
pipenv run flask run

curl localhost:5000/sites

参考