Posts

Showing posts with the label Ansible

Ansible Centos 8 Dnf Module "module" Switch Missing?

Answer : You can install a module (which is essentially a group of packages) by adding a @ prior to the name of the module to the name parameter of the Ansible dnf module. It can be used like this: - name: install the 'Development tools' package group dnf: name: '@Development tools' state: present

Ansible - Print Message - Debug: Msg="line1 \n {{ Var2 }} \n Line3 With Var3 = {{ Var3 }}"

Answer : debug module support array, so you can do like this: debug: msg: - "First line" - "Second line" The output: ok: [node1] => { "msg": [ "First line", "Second line" ] } Or you can use the method from this answer: In YAML, how do I break a string over multiple lines? The most convenient way I found to print multi-line text with debug is: - name: Print several lines of text vars: msg: | This is the first line. This is the second line with a variable like {{ inventory_hostname }}. And here could be more... debug: msg: "{{ msg.split('\n') }}" It splits the message up into an array and debug prints each line as a string. The output is: ok: [example.com] => { "msg": [ "This is the first line.", "This is the second line with a variable like example.com", "And...

Ansible And Git Permission Denied (publickey) At Git Clone

Answer : By reading the documentation for ssh forwarding in ansible. I was able to figure out the solution. The problem was that my ssh keys were not being forwarded because Ansible does not by default forward your keys, even if you have set up the key forwarding on ~/.ssh/conf (I updated my question with the ansible.cfg that I had before fixing the issue). The solution is was to add transport = ssh to ansible.cfg under [defaults] plus running ansible-playbook from the location where ansible.cfg is located and make sure thet the following setting exists in the /etc/ssh/sshd_config of the target box: AllowAgentForwarding yes My ansible.cfg now looks like this: [defaults] transport = ssh [ssh_connection] ssh_args = -o ForwardAgent=yes To clone the private github repo over the remote server, I am doing this: First add the ssh key to your ssh-agent: eval `ssh-agent -s` ssh-add ~/.ssh/my-private-key.pem After that I have modified the ansible.cfg : [defaults] ...

Check If Service Exists With Ansible

Answer : See the service_facts module, new in Ansible 2.5. - name: Populate service facts service_facts: - debug: msg: Docker installed! when: "'docker' in services" Of course I could also just check if the wrapper script exists in /etc/init.d. So this is what I ended up with: - name: Check if Service Exists stat: path=/etc/init.d/{{service_name}} register: service_status - name: Stop Service service: name={{service_name}} state=stopped when: service_status.stat.exists register: service_stopped It would be nice if the "service" module could handle "unrecognized service" errors. This is my approach, using the service command instead of checking for an init script: - name: check for apache shell: "service apache2 status" register: _svc_apache failed_when: > _svc_apache.rc != 0 and ("unrecognized service" not in _svc_apache.stderr) - name: disable apache service: name=...

Ansible. Fast Way To Check Syntax?

Answer : This is expected behaviour according to the documentation: When ansible-playbook is executed with --check it will not make any changes on remote systems. Instead, any module instrumented to support ‘check mode’ (which contains most of the primary core modules, but it is not required that all modules do this) will report what changes they would have made rather than making them. Other modules that do not support check mode will also take no action, but just will not report what changes they might have made. http://docs.ansible.com/ansible/playbooks_checkmode.html If you would like to check the YAML syntax you can use syntax-check. ansible-playbook rds_prod.yml --syntax-check playbook: rds_prod.yml I was looking for the same, but was not satisfied by the --syntax-check option, since it does not work its way down to the roles. A more complete check can be performed with ansible-lint which also includes style-checks. But if you turn off all style-chec...

Ansible And Wget

Answer : Don't use shell-module when there is specialized modules available. In your case: Create directories with file-module: - name: create project directory {{ common.project_dir }} file: state=directory path={{ common.project_dir }} Download files with get_url-module: - name: download sources get_url: url={{ opencv.url }} dest={{ common.project_dir }}/{{ opencv.file }} Note the new module call syntax in the examples above. If you have to use sudo with password remember to give --ask-sudo-pass when needed (see e.g. Remote Connection Information).

Ansible - Create Multiple Folders If Don't Exist

Answer : Using Ansible modules, you don't need to check if something exist or not, you just describe the desired state, so: - name: create directory if they don't exist file: path: "{{ item }}" state: directory owner: root group: root mode: 0775 loop: - /data/directory - /data/another Ansible - Creating multiple folders without changing permissions of previously existing. Working fine for me. Hope this works for you as well just try. --- - name: "Creating multiple by checking folders" hosts: your_host_name tasks: - block: - name: "Checking folders" stat: path: "{{item}}" register: folder_stats with_items: - ["/var/www/f1","/var/www/f2","/var/www/f3","/var/www/f4"] - name: "Creating multiple folders without disturbing previous permissions" file: path: "{{item.item}}" state: direc...

Anisible Pip3 Install Keeps Failing On Remote Service (No Setuptools Found In Remote Host, Please Install It First)

Answer : Ansible needs setuptools to be installed for the version of Python that is being used to run Ansible modules, which, by default, is Python 2. So you need to run pip2 install setuptools or equivalent in order to install setuptools in Python 2.

Accessing Inventory Host Variable In Ansible Playbook

Answer : You are on the right track about hostvars . This magic variable is used to access information about other hosts. hostvars is a hash with inventory hostnames as keys. To access fields of each host, use hostvars['test-1'] , hostvars['test2-1'] , etc. ansible_ssh_host is deprecated in favor of ansible_host since 2.0. So you should first remove "_ssh" from inventory hosts arguments (i.e. to become "ansible_user", "ansible_host", and "ansible_port"), then in your role call it with: {{ hostvars['your_host_group'].ansible_host }} [host_group] host-1 ansible_ssh_host=192.168.0.21 node_name=foo host-2 ansible_ssh_host=192.168.0.22 node_name=bar [host_group:vars] custom_var=asdasdasd You can access host group vars using: {{ hostvars['host_group'].custom_var }} If you need a specific value from specific host, you can use: {{ hostvars[groups['host_group'][0]].node_name }} You should be a...

Ansible Recursive Directory Copy

Answer : file module is not for copying the files, but for setting attributes of files on the target. copy module is for copying. Providing some additional information to the accepted answer.. Recursive copy using directory paths has the following disadvantages: you cannot get changed state information per file copied so --check and --check --diff flags won't show anything you cannot include/exclude specific files/directories to/from the recursion performing corrective changes after the bulk copy will never produce a state with changed=0 and could also affect files that already existed on remote host. There seems to be a more powerful way to perform a recursive copy, which is to use with_filetree combined with when - name: "create-remote-dirs" file: path: /dest/dir/{{item.path}} state: directory mode: '0775' with_filetree: sourceDir/ when: item.state == 'directory' - name: "copy-files" copy: src...

Ansible Include Task Only If File Exists

Answer : The with_first_found conditional can accomplish this without a stat or local_action . This conditional will go through a list of local files and execute the task with item set to the path of the first file that exists. Including skip: true on the with_first_found options will prevent it from failing if the file does not exist. Example: - hosts: localhost connection: local gather_facts: false tasks: - include: "{{ item }}" with_first_found: - files: - /home/user/optional/file.yml skip: true Thanks all for your help! I'm aswering my own question after finally trying all responses and my own question's code back in today's Ansible: ansible 2.0.1.0 My original code seems to work now, except the optional file I was looking was in my local machine, so I had to run stat through local_action and set become: no for that particular tasks, so ansible wouldn't attempt to do sudo in my local machine ...

Ansible Command Module Says That '|' Is Illegal Character

Answer : From the doc: command - Executes a command on a remote node The command module takes the command name followed by a list of space-delimited arguments. The given command will be executed on all selected nodes. It will not be processed through the shell, so variables like $HOME and operations like "<", ">", "|", and "&" will not work (use the shell module if you need these features). shell - Executes a commands in nodes The shell module takes the command name followed by a list of space-delimited arguments. It is almost exactly like the command module but runs the command through a shell (/bin/sh) on the remote node. Therefore you have to use shell: dpkg -l | grep python-apt . read about the command module in the Ansible documentation: It will not be processed through the shell, so .. operations like "<", ">", "|", and "&" will not work As it recommends, use t...

Check If Strings Are Equals And Ternary Operator In Ansible

Answer : Solved! service_type: "{{ 'NodePort' if expose_service == 'true' else 'ClusterIP' }}" In your example you are applying the ternary filter to the 'true' string. Effectively you are comparing the value of expose_service with the string 'NodePort' and always get false in result. You need to enclose the equality operator-clause in parentheses: - include: deploy_new.yml vars: service_type: "{{ (expose_service == true) | ternary('NodePort', 'ClusterIP') }}" when: service_up|failed The other other two points addressed in this answer: you use the string 'true' instead of Boolean when directive is on wrong indentation level (you effectively pass the variable called when )

Ansible: Restart Service Only If It Was Running

Answer : Register a variable when config is updated. Register another variable when you check if a service is running. Call service restart handler only if both variables are true. As for specifics of various OS, you could have conditional execution based on family/distribution from host facts. Ansible's service: module doesn't provide a mechanism for checking if a service is already running or not. Therefore you'll have to resort to using something like this via the shell: module to determine first if the service is running. Example Here I'm detecting whether WebSphere or Tomcat8 are running, and then restarting the appropriate service based on its status. --- # handles tomcat8 - name: is tomcat8 already running? shell: service tomcat8 status warn=false register: _svc_tomcat8 failed_when: _svc_tomcat8.rc != 0 and ("unrecognized service" not in _svc_tomcat8.stderr) ignore_errors: true - name: restart tomcat8 if running service: name=to...

Ansible Print Debug Msg Variable

Answer : Solution 1: Try this: - name: Print mosh version debug: "msg=Mosh Version: '{{ mosh_version.stdout }}'" More info in http://docs.ansible.com/YAMLSyntax.html#gotchas Edited: Something like this works perfect for me: - name: Check Ansible version command: ansible --version register: ansibleVersion - name: Print version debug: msg: "Ansible Version: {{ ansibleVersion.stdout }}" http://pastie.org/private/cgeqjucn3l5kxhkkyhtpta Solution 2: Simplest answer - debug: var=mosh_version.stdout Solution 3: I have displayed variable and message in the debug same task. Ansible Task - name: Report the /boot/initramfs file status for latest installed kernel debug: msg: "{{ ansible_hostname }} = {{INITRAMFS_LAST_KERNEL.stdout}}" Output TASK [os-upgrade.linux : Report the /boot/initramfs file status for latest installed kernel] ******************************************* ok: [ANSIBLENODE] => { ...

Adding A User To An Additional Group Using Ansible

Answer : Solution 1: If {{ user }} already exists in the system, you should use the following to just add it to a group: - name: adding existing user '{{ user }}' to group sudo user: name: '{{ user }}' groups: sudo append: yes To add it to a set of groups, you can use a comma separated list, for example groups: admin,sudo . Just beware that if you omit append: yes , your user will be removed from all other groups, according to the usermod man page. That would useful if you want to use a specific list of groups a user should belong to. Solution 2: According to the User module you can use this: - name: Adding user {{ user }} user: name={{ user }} group={{ user }} shell=/bin/bash password=${password} groups=sudo append=yes You can just add the groups=groupname and append=yes to add them to an existing user when you're creating them Solution 3: Please note that {{ user }} was changed to {{ ...

Ansible Synchronize With Wildcard

Answer : This can be done with ansible's with_lines: - name: Install services jar synchronize: src="{{item}}" dest=/opt/company/ with_lines: "find {{ core_repo }}/service-packaging/target/ -name all-services*.jar | grep -v original" Ansible module synchronize uses rsync and supports custom options for rsync through parameter rsync_opts (since 1.6) which could be used to filter file. Example: - name: sync source code synchronize: src: "/path/to/local/src" dest: "{{lookup('env','HOME')}}/remote/src" rsync_opts: - "--include=*.py" - "--exclude=*.pyc" - "--delete"

Ansible: How To Recursively Set Directory And File Permissions

Answer : file: dest=/foo/bar/somedir owner=root group=apache mode=u=rwX,g=rX,o=rX recurse=yes will set directories to 755, and files to 644. The Ansible file/copy modules don't give you the granularity of specifying permissions based on file type so you'd most likely need to do this manually by doing something along these lines: - name: Ensure directories are 0755 command: find {{ path }} -type d -exec chmod 0755 {} \; - name: Ensure files are 0644 command: find {{ path }} -type f -exec chmod 0644 {} \; These would have the effect of recursing through {{ path }} and changing the permissions of every file or directory to the specified permissions. Source: https://stackoverflow.com/a/28782805/1306186 If you want to use the module file in ansible, you can: file: dest=/foo/bar/somedir owner=root group=apache mode=0644 recurse=yes file: dest=/foo/bar/somedir owner=root group=apache mode=0775 With this method you first set all the file...

Ansible Date Variable

Answer : The command ansible localhost -m setup basically says "run the setup module against localhost", and the setup module gathers the facts that you see in the output. When you run the echo command these facts don't exist since the setup module wasn't run. A better method to testing things like this would be to use ansible-playbook to run a playbook that looks something like this: - hosts: localhost tasks: - debug: var=ansible_date_time - debug: msg="the current date is {{ ansible_date_time.date }}" Because this runs as a playbook facts for localhost are gathered before the tasks are run. The output of the above playbook will be something like this: PLAY [localhost] ************************************************** GATHERING FACTS *************************************************************** ok: [localhost] TASK: [debug var=ansible_date_time] ******************************************* ok: [localhost] => { "a...