Run command on the Ansible host

后端 未结 8 1296
小鲜肉
小鲜肉 2020-12-22 14:45

Is it possible to run commands on the Ansible host?

My scenario is that I want to take a checkout from a git server that is hosted internally (and isn\'t accessible

8条回答
  •  萌比男神i
    2020-12-22 15:23

    From the Ansible documentation:

    Delegation This isn’t actually rolling update specific but comes up frequently in those cases.

    If you want to perform a task on one host with reference to other hosts, use the ‘delegate_to’ keyword on a task. This is ideal for placing nodes in a load balanced pool, or removing them. It is also very useful for controlling outage windows. Be aware that it does not make sense to delegate all tasks, debug, add_host, include, etc always get executed on the controller. Using this with the ‘serial’ keyword to control the number of hosts executing at one time is also a good idea:

    ---
    
    - hosts: webservers
      serial: 5
    
      tasks:
    
      - name: take out of load balancer pool
        command: /usr/bin/take_out_of_pool {{ inventory_hostname }}
        delegate_to: 127.0.0.1
    
      - name: actual steps would go here
        yum:
          name: acme-web-stack
          state: latest
    
      - name: add back to load balancer pool
        command: /usr/bin/add_back_to_pool {{ inventory_hostname }}
        delegate_to: 127.0.0.1
    

    These commands will run on 127.0.0.1, which is the machine running Ansible. There is also a shorthand syntax that you can use on a per-task basis: ‘local_action’. Here is the same playbook as above, but using the shorthand syntax for delegating to 127.0.0.1:

    ---
    
    # ...
    
      tasks:
    
      - name: take out of load balancer pool
        local_action: command /usr/bin/take_out_of_pool {{ inventory_hostname }}
    
    # ...
    
      - name: add back to load balancer pool
        local_action: command /usr/bin/add_back_to_pool {{ inventory_hostname }}
    

    A common pattern is to use a local action to call ‘rsync’ to recursively copy files to the managed servers. Here is an example:

    ---
    # ...
      tasks:
    
      - name: recursively copy files from management server to target
        local_action: command rsync -a /path/to/files {{ inventory_hostname }}:/path/to/target/
    

    Note that you must have passphrase-less SSH keys or an ssh-agent configured for this to work, otherwise rsync will need to ask for a passphrase.

提交回复
热议问题