如何将AWX项目克隆路径传入Ansible Playbook以执行Docker操作?
Great question! When working with Ansible AWX (now part of Ansible Automation Platform Controller), there's a clean, maintainable way to grab your project's cloned path without hardcoding it—perfect for your Docker build step.
The Solution: Use Ansible's Built-in {{ playbook_dir }} Variable
AWX clones your Git SCM project into /var/lib/awx/project by default, and Ansible has a magic built-in variable called playbook_dir that points directly to the directory where your running Playbook is stored. That's exactly the path you need!
You can use this variable in two ways for your Docker build: either specify it as the build context directly, or set it as the working directory for the command. Also, a quick heads-up: your original docker run uses -it, which will fail in AWX's non-interactive environment—swap that for -d to run the container in the background instead.
Here's your updated Playbook:
--- - hosts: all sudo: yes remote_user: ubuntu gather_facts: no tasks: - name : Build test-api Docker image become: yes become_user: root # Option 1: Explicitly pass the project path as build context command : docker build -t "test-api" "{{ playbook_dir }}" # Option 2: Set the working directory, so "." refers to the project path # command : docker build -t "test-api" . # args: # chdir: "{{ playbook_dir }}" - name: Run test-api container in background become: yes become_user: root command : docker run -d -p 80:9001 --name api test-api
Extra Tips for Reliability
- Avoid hardcoding paths! Hardcoding
/var/lib/awx/projectworks now, but if your AWX setup ever changes (like a custom project storage path), your Playbook breaks. Usingplaybook_dirmakes it environment-agnostic. - Ditch
-itfor non-interactive environments AWX runs Playbooks without an interactive terminal, so-itwill cause your container to crash immediately.-druns it detached, which is the right fit for automation. - Consider using dedicated Docker modules (optional) If you install the
community.dockercollection, using modules likedocker_imageanddocker_containeris more robust than rawcommandcalls—they handle state checks, error handling, and idempotency better. Here's how that would look:- name: Build Docker image with dedicated module community.docker.docker_image: name: test-api build: path: "{{ playbook_dir }}" state: present - name: Run Docker container with dedicated module community.docker.docker_container: name: api image: test-api ports: - "80:9001" state: started detach: yes
内容的提问来源于stack exchange,提问作者Frodo

