我有下面的剧本,问题是,应该启动进程的最后一个任务没有以 NGINX_USER 身份运行进程,它总是以 root 身份运行,而这在任何地方都没有指定。我用 进行检查ps aux | grep nginx
。当它这样做时,我得到了一个Forbidden error
。
当我尝试强制它成为用户(像注释掉的代码中那样)时,它会卡住并且无法完成。
如何确保 ansbile 始终以正确的用户运行
- name: Install Nginx Ubuntu
hosts: all
remote_user: "{{ NGINX_USER }}"
become: yes
become_method: sudo
gather_facts: no
connection: ssh
vars:
NGINX_VERSION: nginx-1.17.10
NGINX_SBIN_PATH: /usr/sbin/
NGINX_ERROR_LOG_PATH: /var/log/nginx/error.log
NGINX_HTTP_LOG_PATH: /var/log/nginx/access.log
NGINX_PID_PATH: /var/run/nginx.pid
vars_files:
- ../vars/global.yaml
tasks:
- name: Check if Nginx Exists
stat: path=/etc/init.d/nginx
register: nginx_status
- name: Stop nginx Service
service: name=nginx state=stopped
when: nginx_status.stat.exists
register: service_stopped
- name: Make sure a systemd is not running
systemd:
state: stopped
name: nginx
- name: Install aptitude using apt
apt:
name: aptitude
state: latest
update_cache: yes
force_apt_get: yes
- name: Update apt repo
apt:
update_cache: yes
cache_valid_time: 3600
- name: Install required system packages
apt: name={{ item }} state=latest update_cache=yes
loop:
[
"build-essential",
"libpcre3",
"libpcre3-dev",
"zlib1g",
"zlib1g-dev",
"libssl-dev",
]
- name: Download nginx source
get_url:
url: "http://nginx.org/download/{{ NGINX_VERSION }}.tar.gz"
dest: "/tmp/{{ NGINX_VERSION }}.tar.gz"
- name: Unpacking NGINX
unarchive:
copy: no
dest: /tmp/
src: "/tmp/{{ NGINX_VERSION }}.tar.gz"
- name: Configure NGINX source with custom modules
command: "./configure --prefix=/nginx --sbin-path={{ NGINX_SBIN_PATH }} --error-log-path={{ NGINX_ERROR_LOG_PATH }} --http-log-path={{ NGINX_HTTP_LOG_PATH }} --with-pcre
--pid-path={{ NGINX_PID_PATH }} --with-http_ssl_module --with-http_v2_module"
args:
chdir: "/tmp/{{ NGINX_VERSION }}"
- name: Make NGINX
become: yes
shell: make && make install
args:
chdir: "/tmp/{{ NGINX_VERSION }}"
- name: Create directories"
file:
path: "{{ item.dir }}"
state: directory
owner: "{{ item.owner }}"
group: "{{ item.group }}"
mode: "{{ item.mode }}"
with_items:
- { dir: "/usr/local/nginx/html", owner: "{{ SYSTEM_USER }}", group: "{{ SYSTEM_USER_GROUP }}", mode: 755}
- { dir: "/nginx", owner: "{{ NGINX_USER }}", group: "{{ NGINX_USER }}", mode: 755}
- name: Copy nginx files
copy:
src: "{{ item.src }}"
dest: "{{ item.dest }}"
owner: "{{ NGINX_USER }}"
group: "{{ NGINX_USER }}"
mode: 755
with_items:
# - { src: "./conf/nginx.conf", dest: "{{ NGINX_CONF_PATH }}" }
- { src: "./www/", dest: "/nginx/html" }
- { src: "./scripts/nginx.service", dest: "/lib/systemd/system/nginx.service" }
- name: Start NGINX
# become: true
# become_user: "{{ NGINX_USER }}"
# become_method: sudo
systemd:
state: started
name: nginx
答案1
因为您在播放级别指定了“become: yes”,所以每个任务都将以 become_user 身份执行,默认为 root。尝试使用以下命令启动任务become: false
:
- name: Start NGINX
become: false
systemd:
state: started
name: nginx
阅读您的代码时,我怀疑“确保 systemd 没有运行”也会因您显示的设置而失败。