Ansible: Can I execute role from command line?

2019-02-01 08:49发布

问题:

Suppose I have a role called "apache"

Now I want to execute that role on host 192.168.0.10 from the command line from Ansible host

ansible-playbook -i  "192.168.0.10" --role  "path to role"

Is there a way to do that?

回答1:

I am not aware of this feature, but you can use tags to just run one role from your playbook.

roles:
    - {role: 'mysql', tags: 'mysql'}
    - {role: 'apache', tags: 'apache'}

ansible-playbook webserver.yml --tags "apache"


回答2:

There is no such thing in Ansible, but if this is an often use case for you, try this script.
Put it somewhere within your searchable PATH under name ansible-role:

#!/bin/bash

if [[ $# < 2 ]]; then
  cat <<HELP
Wrapper script for ansible-playbook to apply single role.

Usage: $0 <host-pattern> <role-name> [ansible-playbook options]

Examples:
  $0 dest_host my_role
  $0 custom_host my_role -i 'custom_host,' -vv --check
HELP
  exit
fi

HOST_PATTERN=$1
shift
ROLE=$1
shift

echo "Trying to apply role \"$ROLE\" to host/group \"$HOST_PATTERN\"..."

export ANSIBLE_ROLES_PATH="$(pwd)/roles"
export ANSIBLE_RETRY_FILES_ENABLED="False"
ansible-playbook "$@" /dev/stdin <<END
---
- hosts: $HOST_PATTERN
  roles:
    - $ROLE
END


回答3:

With ansible 2.7 you can do this:

include_role:

$ ansible localhost -m include_role -a name=bob
localhost | SUCCESS => {
    "changed": false,
    "include_variables": {
        "name": "bob"
    }
}
localhost | SUCCESS => {
    "msg": "bob"
}

https://github.com/ansible/ansible/pull/43131



回答4:

You could also check ansible-toolbox repository. It will allow you to use something like

ansible-role --host 192.168.0.10 --gather --user centos --become my-role


回答5:

I have written a small Ansible plugin, called auto_tags, that dynamically generates for each role in your playbook a tag of the same name. You can find it here.

After installing it (instructions are in the gist above) you could then execute a specific role with:

ansible-playbook -i "192.168.0.10" --tags "name_of_role"