Using an SSH keyfile with Fabric

后端 未结 8 1497
Happy的楠姐
Happy的楠姐 2020-11-28 18:42

How do you configure fabric to connect to remote hosts using SSH keyfiles (for example, Amazon EC2 instances)?

8条回答
  •  半阙折子戏
    2020-11-28 19:22

    For fabric2 in fabfile use the following:

    from fabric import task, Connection
    
    @task
    def staging(ctx):
        ctx.name = 'staging'
        ctx.user = 'ubuntu'
        ctx.host = '192.1.1.1'
        ctx.connect_kwargs.key_filename = os.environ['ENV_VAR_POINTS_TO_PRIVATE_KEY_PATH']
    
    @task
    def do_something_remote(ctx):
        with Connection(ctx.host, ctx.user, connect_kwargs=ctx.connect_kwargs) as conn:
            conn.sudo('supervisorctl status')
    

    and run it with:

    fab staging do_something_remote
    

    UPDATE:
    For multiple hosts (one host will do also) you can use this:

    from fabric2 import task, SerialGroup
    
    @task
    def staging(ctx):
        conns = SerialGroup(
            'user@10.0.0.1',
            'user@10.0.0.2',
            connect_kwargs=
            {
                'key_filename': os.environ['PRIVATE_KEY_TO_HOST']
            })
        ctx.CONNS = conns
        ctx.APP_SERVICE_NAME = 'google'
    
    @task
    def stop(ctx):
        for conn in ctx.CONNS:
            conn.sudo('supervisorctl stop ' + ctx.APP_SERVICE_NAME)
    

    and run it with fab or fab2:

    fab staging stop
    

提交回复
热议问题