Summary when using Fabric

A summary of the survey on the introduction of Fabric in the system currently being viewed. Described with reference to Official Document. There seems to be a lot of things you can do, but you can't take over unless you keep it simple, so it's about the following. The version I tried is as follows.

Simple execution is executed in the following format

fab -f file name-H host name-u username execution method

Example: fab-f fab_test.py -H 192.168.1.10 -u ubuntu task_name

Basic description

fab_test.py


from fabric.api import *

def task_name():
  run("whoami")
  sudo("whoami")
  with cd("/tmp"):
    run("pwd")

Command content

get Copy the file locally from the target server. Check the return value .succeeded to see if it was successful. .failed seems to store a list of file paths in case of failure.

get("Remote server path","Local path")
r = get('/home/foo/hoge', './')
print(r.succeeded) # =>If True, it succeeds. Fail if False
print(r.failed)

put Copy the file from local to the target server.

put('Local server path','Remote server path')
r = put('./hoge',"/home/foo")
print(r.succeeded) # =>If True, it succeeds. Fail if False

local Execute the command on the local server.

local("pwd")

run Execute the command on the remote server. The user who executes is the user who accessed.

run("whoami")

sudo sudo and execute the command. It will fail if the accessing user does not have sudo privileges.

sudo("whoami")

It is also possible to specify the execution user by describing as follows.

with settings(sudo_user='mysql'):
    sudo("whoami") # prints 'mysql'

open_shell Migrate to the remote server shell and execute the command. Move to interactive as it is.

open_shell("ls")

prompt Accepts input from the user prompt. It seems that validation is also possible. When I entered a character string for the int type, an Exception occurred, so it seems better to validate it with a regular expression.

r = prompt("run command ?")
run(r)

# With validation, i.e. requiring integer input:
prompt('Please specify process nice level: ', key='nice', validate=int)

# With validation against a regular expression:
release = prompt('Please supply a release name',
        validate=r'^\w+-\d+(\.\d+)?$')
        

with cd ("XX"): or with prefix ("YY"):

Prefix all commands with cd XX && or YY &&. I couldn't put su-in front of the prefix, so use the settings mentioned above.

with cd("/etc"):
  run("cat hosts")

with prefix("cd /etc"):
  run("cat hosts")

coloring

Colors can be added by describing as follows. It seems easy to understand if you color success or failure. It is necessary to verify whether it will be colored with Teraterm.

from fabric.colors import *

print(red("This sentence is red, except for " +   
        green("these words, which are green") + "."))

The colors are as follows.

roll

Execute the method only on the server of the target role.

from fabric.api import env

env.roledefs = {
    'web': ['192.168.1.10', '192.168.1.11', '192.168.1.12']
}

@roles('web')
def restart_nginx():
  sudo("service nginx restart ")

The execution is as follows. In the above, @roles ('web') is described before the method, so -R web can be omitted at runtime.

fab -f Executable file[-R roll] task
fab -f fab_test.py -u ubuntu restart_nginx

Make sure the result is an error

There was a procedure called "File is missing" in the procedure, and when I made a script like I did manually, it stopped there. It can be avoided by inserting warn_only = True as shown below.

with settings(warn_only=True):
  result = sudo("ls -l /not/found/path")

[Other sites that may be helpful] https://blog.masu-mi.me/2015/04/11/fabric_tips.html

http://perezvon.hatenablog.com/entry/20091026/1256552181

Recommended Posts

Summary when using Fabric
Precautions when using Chainer
Document summary when using Cloud Firestore from Java
Summary of things that were convenient when using pandas
(Personal) points when using ctypes
Environment variables when using Tkinter
When using optparse with iPython
DEBUG settings when using Django
When using if and when using while
File structure when using serverless-python-requirements
Use configparser when using API
Small speedup when using pytorch
Generate a Docker image using Fabric
A memorandum when using beautiful soup
Variable scope when using internal functions
Proxy measures when using WEB API
Summary if using AWS Lambda (Python)
Sentence summary using BERT [for relatives]
Precautions when using TextBlob trait analysis
Deploy script to jboss using fabric
Precautions when using codecs and pandas
Precautions when using the urllib.parse.quote function
Tweet WakaTime Summary using AWS Lambda
[Python] Be careful when using print
Precautions when using phantomjs from python
ResourceWarning when using requests: unclosed workaround
When using MeCab with virtualenv python
Precautions when using six with Python 2.5
[VS Code] ~ Tips when using python ~
When using regular expressions in Python
fabric
Knowledge when making a bot using discord.py
Periodic execution processing when using tkinter [Python3]
What I got into when using Tensorflow-gpu
Usual processing notes when using Google Colaboratory
What Rubyist should know when using pyenv
Favicon placement (when using Python, Flask, Heroku)
[python, multiprocessing] Behavior for exceptions when using multiprocessing
Precautions when using for statements in pandas
DB settings when using Django + SQLAlchemy + Alembic
Summary of snippets when developing with Go
Error, warning when using TensorFlow on Mac