All topics

DevOps and SRE practice

39 questions with answers.

  1. What is a Pem file and how does it differ from other OpenSSL Generated Key File Formats?

    SSL has been around for long enough you'd think that there would be agreed upon container formats. And you're right, there are. Too many standards as it happens. In the end, all of these are different ways to encode Abstract Syntax Notation 1 (ASN.1) formatted data — which happens to be the format x509 certificates are defined in — in machine-readable ways.

    • .csr - This is a Certificate Signing Request. Some applications can generate these for submission to certificate-authorities. The actual format is PKCS10 which is defined in RFC 2986. It includes some/all of the key details of the requested certificate such as subject, organization, state, whatnot, as well as the public key of the certificate to get signed. These get signed by the CA and a certificate is returned. The returned certificate is the public certificate (which includes the public key but not the private key), which itself can be in a couple of formats.
    • .pem - Defined in RFC 1422 (part of a series from 1421 through 1424) this is a container format that may include just the public certificate (such as with Apache installs, and CA certificate files /etc/ssl/certs), or may include an entire certificate chain including public key, private key, and root certificates. Confusingly, it may also encode a CSR (e.g. as used here) as the PKCS10 format can be translated into PEM. The name is from Privacy Enhanced Mail (PEM), a failed method for secure email but the container format it used lives on, and is a base64 translation of the x509 ASN.1 keys. How certificate chains are encoded depends on what's reading the .pem files, it isn't standardized.
    • .key - This is a (usually) PEM formatted file containing just the private-key of a specific certificate and is merely a conventional name and not a standardized one. In Apache installs, this frequently resides in /etc/ssl/private. The rights on these files are very important, and some programs will refuse to load these certificates if they are set wrong. Technically, this is a base64 version of a PKCS8-formatted key (RFC 5958).
    • .pkcs12 .pfx .p12 - Originally defined by RSA in the Public-Key Cryptography Standards (abbreviated PKCS), the "12" variant was originally enhanced by Microsoft, and later submitted as RFC 7292. This is a password-protected container format that contains both public and private certificate pairs. Java 9 and newer (2017 onwards) defaults to these files over the older proprietary .jks or PKCS files (see below). Unlike .pem files, this container is fully encrypted and has standard ways of encoding whole chains. Openssl can turn this into a .pem file with both public and private keys: openssl pkcs12 -in file-to-convert.p12 -out converted-file.pem -nodes

    A few other formats that show up from time to time:

    Read the rest at the sourceFrom Server Fault: asked by Noah Goodrich, answered by sysadmin1138 (CC BY-SA 4.0)

  2. How can I sort du -h output by size?

    As of GNU coreutils 7.5 released in August 2009, sort allows a -h parameter, which allows numeric suffixes of the kind produced by du -h:

    du -hs * | sort -h
    

    To sort in reverse order (largest files first) add -r option:

    du -hs * | sort -hr
    

    If you are using a sort that does not support -h, you can install GNU Coreutils. E.g. on an older Mac OS X:

    brew install coreutils
    du -hs * | gsort -h
    

    Parameter description from sort manual:

    -h, --human-numeric-sort
        compare human readable numbers (e.g., 2K 1G)
    -r, --reverse
        reverse the result of comparisons 
    

    From Server Fault: asked by Tom Feiner, answered by ptman (CC BY-SA 4.0)

  3. How to determine if a bash variable is empty?

    This will return true if a variable is unset or set to the empty string ("").

    if [ -z "${VAR}" ];
    

    From Server Fault: asked by Brent , answered by duffbeer703 (CC BY-SA 4.0)

  4. Can you ping a specific port of a machine?

    You can't ping ports, as Ping is using ICMP which is an internet layer protocol that doesn't have ports. Ports belong to the transport layer protocols like TCP and UDP.

    However, you could use nmap to see whether ports are open or not

    nmap -p 80 example.com
    

    Edit: As flokra mentioned, nmap is more than just a ping-for-ports-thingy. It's the security auditers and hackers best friend and comes with tons of cool options. Check the doc for all possible flags.

    From Server Fault: asked by Davie, answered by sfussenegger (CC BY-SA 4.0)

  5. Can scp copy directories recursively?

    Yup, use -r:

    scp -rp sourcedirectory user@dest:/path
    
    • -r means recursive
    • -p preserves modification times, access times, and modes from the original file.

    Note: This creates the sourcedirectory inside /path thus the files will be in /path/sourcedirectory

    From Server Fault: asked by kernel, answered by dmourati (CC BY-SA 3.0)

  6. How to automate SSH login with password?
    $ sudo apt-get install sshpass
    $ sshpass -p your_password ssh user@hostname
    

    From Server Fault: asked by Cage, answered by weekens (CC BY-SA 3.0)

  7. How do I deal with a compromised server?

    It's hard to give specific advice from what you've posted here but I do have some generic advice based on a post I wrote ages ago back when I could still be bothered to blog.

    Don't Panic

    First things first, there are no "quick fixes" other than restoring your system from a backup taken prior to the intrusion, and this has at least two problems.

    1. It's difficult to pinpoint when the intrusion happened.
    2. It doesn't help you close the "hole" that allowed them to break in last time, nor deal with the consequences of any "data theft" that may also have taken place.

    This question keeps being asked repeatedly by the victims of hackers breaking into their web server. The answers very rarely change, but people keep asking the question. I'm not sure why. Perhaps people just don't like the answers they've seen when searching for help, or they can't find someone they trust to give them advice. Or perhaps people read an answer to this question and focus too much on the 5% of why their case is special and different from the answers they can find online and miss the 95% of the question and answer where their case is near enough the same as the one they read online.

    That brings me to the first important nugget of information. I really do appreciate that you are a special unique snowflake. I appreciate that your website is too, as it's a reflection of you and your business or at the very least, your hard work on behalf of an employer. But to someone on the outside looking in, whether a computer security person looking at the problem to try and help you or even the attacker himself, it is very likely that your problem will be at least 95% identical to every other case they've ever looked at.

    Don't take the attack personally, and don't take the recommendations that follow here or that you get from other people personally. If you are reading this after just becoming the victim of a website hack then I really am sorry, and I really hope you can find something helpful here, but this is not the time to let your ego get in the way of what you need to do.

    You have just found out that your server(s) got hacked. Now what?

    Do not panic. Absolutely do not act in haste, and absolutely do not try and pretend things never happened and not act at all.

    First: understand that the disaster has already happened. This is not the time for denial; it is the time to accept what has happened, to be realistic about it, and to take steps to manage the consequences of the impact.

    Some of these steps are going to hurt, and (unless your website holds a copy of my details) I really don't care if you ignore all or some of these steps, that's up to you. But following them properly will make things better in the end. The medicine might taste awful but sometimes you have to overlook that if you really want the cure to work.

    Stop the problem from becoming worse than it already is:

    1. The first thing you should do is disconnect the affected systems from the Internet. Whatever other problems you have, leaving the system connected to the web will only allow the attack to continue. I mean this quite literally; get someone to physically visit the server and unplug network cables if that is what it takes, but disconnect the victim from its muggers before you try to do anything else.
    2. Change all your passwords for all accounts on all computers that are on the same network as the compromised systems. No really. All accounts. All computers. Yes, you're right, this might be overkill; on the other hand, it might not. You don't know either way, do you?
    3. Check your other systems. Pay special attention to other Internet facing services, and to those that hold financial or other commercially sensitive data.
    4. If the system holds anyone's personal data, immediately inform the person responsible for data protection (if that's not you) and URGE a full disclosure. I know this one is tough. I know this one is going to hurt. I know that many businesses want to sweep this kind of problem under the carpet but the business is going to have to deal with it - and needs to do so with an eye on any and all relevant privacy laws.

    Read the rest at the sourceFrom Server Fault: asked by gunwin, answered by Rob Moir (CC BY-SA 3.0)

  8. What exactly do the colors in htop status bars mean?

    Hitting F1 or h will show you the key. But for reference, the default colors are:

    CPU:

    • Blue = Low priority threads
    • Green = Normal priority threads
    • Red = Kernel threads

    Memory:

    • Green = Used memory
    • Blue = Buffers
    • Yellow/Orange = Cache

    There are a couple of different color-schemes available, you can see them through hitting F2.

    From Server Fault: asked by tobym, answered by sysadmin1138 (CC BY-SA 3.0)

  9. ssh returns "Bad owner or permissions on ~/.ssh/config"

    I needed to have rw for user only permissions on config. This fixed it.

    chmod 600 ~/.ssh/config
    

    As others have noted below, it could be the file owner. (upvote them!)

    chown $USER ~/.ssh/config
    

    If your whole folder has invalid permissions here's a table of possible permissions:

    Path Permission
    .ssh directory (code) 0700 (drwx------)
    private keys (ex: id_rsa) (code) 0600 (-rw-------)
    config 0600 (-rw-------)
    public keys (*.pub ex: id_rsa.pub) 0644 (-rw-r--r--)
    authorized_keys (code) 0644 (-rw-r--r--)
    known_hosts 0644 (-rw-r--r--)

    Sources:

    From Server Fault: asked by Robert, answered by Robert (CC BY-SA 4.0)

  10. In Nginx, how can I rewrite all http requests to https while maintaining sub-domain?

    Correct way in new versions of nginx

    Turn out my first answer to this question was correct at certain time, but it turned into another pitfall - to stay up to date please check Taxing rewrite pitfalls

    ## Redirect all HTTP traffic to HTTPS
    server {
      listen          [::]:80 default_server;
      listen               80 default_server;
      server_name     _;
      return          307 https://$host$request_uri;
    }
    server {
      listen         443 ssl http2 quic;
      server_name    my.domain.com;
      # add Strict-Transport-Security to prevent man in the middle attacks
      add_header Strict-Transport-Security "max-age=31536000" always; 
      ...
    }
    

    From Server Fault: asked by MikeN, answered by Saif Bechan (CC BY-SA 4.0)

  11. What is the difference between double and single square brackets in bash?

    There are several differences. In my opinion, a few of the most important are:

    1. [ is a builtin in Bash and many other modern shells. The builtin [ is similar to test with the additional requirement of a closing ]. The builtins [ and test imitate the functionality /bin/[ and /bin/test along with their limitations so that scripts would be backwards compatible. The original executables still exist mostly for POSIX compliance and backwards compatibility. Running the command type [ in Bash indicates that [ is interpreted as a builtin by default. (Note: which [ only looks for executables on the PATH and is equivalent to type -P [. You can execute type --help for details)
    2. [[ is not as compatible, it won't necessarily work with whatever /bin/sh points to. So [[ is the more modern Bash / Zsh / Ksh option.
    3. Because [[ is built into the shell and does not have legacy requirements, you don't need to worry about word splitting based on the IFS variable to mess up on variables that evaluate to a string with spaces. Therefore, you don't really need to put the variable in double quotes.

    For the most part, the rest is just some nicer syntax. To see more differences, I recommend this link to an FAQ answer: What is the difference between test, [ and [[ ?. In fact, if you are serious about bash scripting, I recommend reading the entire wiki, including the FAQ, Pitfalls, and Guide. The test section from the guide section explains these differences as well, and why the author(s) think [[ is a better choice if you don't need to worry about being as portable. The main reasons are:

    1. You don't have to worry about quoting the left-hand side of the test so that it actually gets read as a variable.
    2. You don't have to escape less than and greater than < > with backslashes in order for them not to get evaluated as input redirection, which can really mess some stuff up by overwriting files. This again goes back to [[ being a builtin. If [ (test) is an external program the shell would have to make an exception in the way it evaluates < and > only if /bin/test is being called, which wouldn't really make sense.

    From Server Fault: asked by 0x89, answered by Kyle Brandt (CC BY-SA 4.0)

  12. mysqldump throws: Unknown table 'COLUMN_STATISTICS' in information_schema (1109)

    This is due to a new flag that is enabled by default in mysqldump 8. You can disable it by adding --column-statistics=0. The command will be something like:

    mysqldump --column-statistics=0 --host=<server> --user=<user> --password=<password> 
    

    Check this link for more information. To disable column statistics by default, you can add

    [mysqldump]
    column-statistics=0
    

    to a MySQL config file, go to /etc/my.cnf, ~/.my.cnf, or directly to /etc/mysql/mysql.cnf.

    From Server Fault: asked by manifestor, answered by cristhiank (CC BY-SA 4.0)

  13. How does IPv4 Subnetting Work?

    IP subnets exist to allow routers to choose appropriate destinations for packets. You can use IP subnets to break up larger networks for logical reasons (firewalling, etc), or physical need (smaller broadcast domains, etc).

    Simply put, though, IP routers use your IP subnets to make routing decisions. Understand how those decisions work, and you can understand how to plan IP subnets.

    Counting to 1

    If you are already fluent in binary (base 2) notation you can skip this section.

    For those of you who are left: Shame on you for not being fluent in binary notation!

    Yes, that may be a bit harsh. It's really, really easy to learn to count in binary, and to learn shortcuts to convert binary to decimal and back. You really should know how to do it.

    Counting in binary is so simple because you only have to know how to count to 1!

    Think of a car's "odometer", except that unlike a traditional odometer each digit can only count up to 1 from 0. When the car is fresh from the factory the odometer reads "00000000".

    When you've driven your first mile the odometer reads "00000001". So far, so good.

    When you've driven your second mile the first digit of the odometer rolls back over to "0" (since its maximum value is "1") and the second digit of the odometer rolls over to "1", making the odometer read "00000010". This looks like the number 10 in decimal notation, but it's actually 2 (the number of miles you've driven the car so far) in binary notation.

    When you've driven the third mile the odometer reads "00000011", since the first digit of the odometer turns again. The number "11", in binary notation, is the same as the decimal number 3.

    Finally, when you've driven your fourth mile both digits (which were reading "1" at the end of the third mile) roll back over to zero position, and the 3rd digit rolls up to the "1" position, giving us "00000100". That's the binary representation of the decimal number 4.

    You can memorize all of that if you want, but you really only need to understand how the little odometer "rolls over" as the number it's counting gets bigger. It's exactly the same as a traditional decimal odometer's operation, except that each digit can only be "0" or "1" on our fictional "binary odometer".

    To convert a decimal number to binary you could roll the odometer forward, tick by tick, counting aloud until you've rolled it a number of times equal to the decimal number you want to convert to binary. Whatever is displayed on the odometer after all that counting and rolling would be the binary representation of the decimal number you counted up to.

    Since you understand how the odometer rolls forward you'll also understand how it rolls backward, too. To convert a binary number displayed on the odometer back to decimal you could roll the odometer back one tick at a time, counting aloud until the odometer reads "00000000". When all that counting and rolling is done, the last number you say aloud would be the decimal representation of the binary number the odometer started with.

    Converting values between binary and decimal this way would be very tedious. You could do it, but it wouldn't be very efficient. It's easier to learn a little algorithm to do it faster.

    A quick aside: Each digit in a binary number is known as a "bit". That's "b" from "binary" and "it" from "digit". A bit is a bnary digit.

    Converting a binary number like, say, "1101011" to decimal is a simple process with a handy little algorithm.

    Start by counting the number of bits in the binary number. In this case, there are 7. Make 7 divisions on a sheet of paper (in your mind, in a text file, etc) and begin filling them in from right to left. In the rightmost slot, enter the number "1", because we'll always start with "1". In the next slot to the left enter double the value in the slot to the right (so, "2" in the next one, "4" in the next one) and continue until all the slots are full. (You'll end up memorizing these numbers, which are the powers of 2, as you do this more and more. I'm alright up to 131,072 in my head but I usually need a calculator or paper after that).

    So, you should have the following on your paper in your little slots.

     64    |    32    |    16    |    8    |    4    |    2    |    1    |
    

    Read the rest at the sourceFrom Server Fault: asked by Kyle Brandt, answered by Evan Anderson (CC BY-SA 4.0)

  14. Something is burning in the server room; how can I quickly identify what it is?

    The general consensus seems to be that the answer to your question comes in two parts:

    How do we find the source of the funny burning smell?

    You've got the "How" pretty well nailed down:

    • The "Sniff Test"
    • Look for visible smoke/haze
    • Walk the room with a thermal (IR) camera to find hot spots
    • Check monitoring and device panels for alerts

    You can improve your chances of finding the problem quickly in a number of ways - improved monitoring is often the easiest. Some questions to ask:

    • Do you get temperature and other health alerts from your equipment?
    • Are your UPS systems reporting faults to your monitoring system?
    • Do you get current-draw alarms from your power distribution equipment?
    • Are the room smoke detectors reporting to the monitoring system? (and can they?)

    When should we troubleshoot versus hitting the Big Red Switch?

    This is a more interesting question.
    Hitting the big red switch can cost your company a huge amount of money in a hurry: Clean agent releases can be into the tens of thousands of dollars, and the outage / recovery costs after an emergency power off (EPO, "dropping the room") can be devastating.
    You do not want to drop a datacenter because a capacitor in a power supply popped and made the room smell.

    Conversely, a fire in a server room can cost your company its data/equipment, and more importantly your staff's lives.
    Troubleshooting "that funny burning smell" should never take precedence over safety, so it's important to have some clear rules about troubleshooting "pre-fire" conditions.

    The guidelines that follow are my personal limitations that I apply in absence of (or in addition to) any other clearly defined procedure/rules - they've served me well and they may help you, but they could just as easily get me killed or fired tomorrow, so apply them at your own risk.

    1. If you see smoke or fire, drop the room
      This should go without saying but let's say it anyway: If there is an active fire (or smoke indicating that there soon will be) you evacuate the room, cut the power, and discharge the fire suppression system.
      Exceptions may exist (exercise some common sense), but this is almost always the correct action.

    2. If you're proceeding to troubleshoot, always have at least one other person involved
      This is for two reasons. First, you do not want to be wandering around in a datacenter and all of a sudden have a rack go up in the row you're walking down and nobody knows you're there. Second, the other person is your sanity check on troubleshooting versus dropping the room, and should you make the call to hit the Big Red Switch you have the benefit of having a second person concur with the decision (helps to avoid the career-limiting aspects of such a decision if someone questions it later).

    3. Exercise prudent safety measures while troubleshooting
      Make sure you always have an escape path (an open end of a row and a clear path to an exit).
      Keep someone stationed at the EPO / fire suppression release.
      Carry a fire extinguisher with you (Halon or other clean-agent, please).
      Remember rule #1 above.
      When in doubt, leave the room. Take care about your breathing: use a respirator or an oxygen mask. This might save your health in case of chemical fire.

    4. Set a limit and stick to it
      More accurately, set two limits:

      • Condition ("How much worse will I let this get?"), and
      • Time ("How long will I keep trying to find the problem before its too risky?").

      The limits you set can also be used to let your team begin an orderly shutdown of the affected area, so when you DO pull power you're not crashing a bunch of active machines, and your recovery time will be much shorter, but remember that if the orderly shutdown is taking too long you may have to let a few systems crash in the name of safety.

    5. Trust your gut
      If you are concerned about safety at any time, call the troubleshooting off and clear the room.
      You may or may not drop the room based on a gut feeling, but regrouping outside the room in (relative) safety is prudent.

    Read the rest at the sourceFrom Server Fault: asked by Chad Harrison, answered by voretaq7 (CC BY-SA 3.0)

  15. Displaying a remote SSL certificate details using CLI tools

    You should be able to use OpenSSL for your purpose:

    echo | openssl s_client -showcerts -servername gnupg.org -connect gnupg.org:443 2>/dev/null | openssl x509 -inform pem -noout -text
    

    That command connects to the desired website and pipes the certificate in PEM format on to another openssl command that reads and parses the details.

    (Note that "redundant" -servername parameter is necessary to make openssl do a request with SNI support.)

    From Server Fault: asked by Adam Matan, answered by Pedro Perez (CC BY-SA 3.0)

  16. How to set environment variable in systemd service?

    Times change and so do best practices.

    The current best way to do this is to run systemctl edit myservice, which will create an override file for you or let you edit an existing one.

    In normal installations this will create a directory /etc/systemd/system/myservice.service.d, and inside that directory create a file whose name ends in .conf (typically, override.conf), and in this file you can add to or override any part of the unit shipped by the distribution.

    For instance, in a file /etc/systemd/system/myservice.service.d/myenv.conf:

    [Service]
    Environment="SECRET=pGNqduRFkB4K9C2vijOmUDa2kPtUhArN"
    Environment="ANOTHER_SECRET=JP8YLOc2bsNlrGuD6LVTq7L36obpjzxd"
    

    Also note that if the directory exists and is empty, your service will be disabled! If you don't intend to put something in the directory, ensure that it does not exist.

    For reference, the old way was:

    The recommended way to do this is to create a file /etc/sysconfig/myservice which contains your variables, and then load them with EnvironmentFile.

    For complete details, see Fedora's documentation on how to write a systemd script.

    From Server Fault: asked by lfagundes, answered by Michael Hampton (CC BY-SA 4.0)

  17. How do I change my private key passphrase?

    To change the passphrase on your default key:

    $ ssh-keygen -p
    

    If you need to specify a key, pass the -f option:

    $ ssh-keygen -p -f ~/.ssh/id_rsa
    

    then provide your old and new passphrase (twice) at the prompts. (Use ~/.ssh/id_rsa if you have an RSA key.)

    More details from man ssh-keygen:

    [...]
    SYNOPSIS
       ssh-keygen  [-q]  [-a  rounds]  [-b  bits] [-C comment] [-f output_keyfile] [-m format] [-N new_passphrase] [-O option]
                  [-t ecdsa | ecdsa-sk | ed25519 | ed25519-sk | rsa] [-w provider] [-Z cipher]
       ssh-keygen -p [-a rounds] [-f keyfile] [-m format] [-N new_passphrase] [-P old_passphrase] [-Z cipher]
    [...]
         -f filename
                 Specifies the filename of the key file.
    [...]
         -N new_passphrase
                 Provides the new passphrase.
         -P passphrase
                 Provides the (old) passphrase.
         -p      Requests changing the passphrase of a private key file instead of
                 creating a new private key.  The program will prompt for the file
                 containing the private key, for the old passphrase, and twice for
                 the new passphrase.
    [...]
    

    From Server Fault: asked by kch, answered by Mike Mazur (CC BY-SA 4.0)

  18. How to run a server on port 80 as a normal user on Linux?

    Short answer: you can't. Ports below 1024 can be opened only by root. As per comment - well, you can, using CAP_NET_BIND_SERVICE, but that approach, applied to java bin will make any java program to be run with this setting, which is undesirable, if not a security risk.

    The long answer: you can redirect connections on port 80 to some other port you can open as normal user.

    Run as root:

    # iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
    

    As loopback devices (like localhost) do not use the prerouting rules, if you need to use localhost, etc., add this rule as well (thanks @Francesco):

    # iptables -t nat -I OUTPUT -p tcp -d 127.0.0.1 --dport 80 -j REDIRECT --to-ports 8080
    

    NOTE: The above solution is not well suited for multi-user systems, as any user can open port 8080 (or any other high port you decide to use), thus intercepting the traffic. (Credits to CesarB).

    EDIT: as per comment question - to delete the above rule:

    # iptables -t nat --line-numbers -n -L
    

    This will output something like:

    Chain PREROUTING (policy ACCEPT)
    num  target     prot opt source               destination         
    1    REDIRECT   tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:8080 redir ports 8088
    2    REDIRECT   tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:80 redir ports 8080
    

    The rule you are interested in is nr. 2, so to delete it:

    # iptables -t nat -D PREROUTING 2
    

    From Server Fault: asked by Deepak Mittal, answered by Sunny (CC BY-SA 3.0)

  19. Why is my crontab not working, and how can I troubleshoot it?

    How to fix all of your crontab related woes/problems (Linux)

    This is a community wiki, if you notice anything incorrect with this answer or have additional information then please edit it.

    First, basic terminology:

    • cron(8) is the daemon that executes scheduled commands.
    • crontab(1) is the program used to modify user crontab(5) files.
    • crontab(5) is a per user file that contains instructions for cron(8).

    Next, education about cron:

    Every user on a system may have their own crontab file. The location of the root and user crontab files are system dependant but they are generally below /var/spool/cron.

    There is a system-wide /etc/crontab file, the /etc/cron.d directory may contain crontab fragments which are also read and actioned by cron. Some Linux distributions (eg, Red Hat) also have /etc/cron.{hourly,daily,weekly,monthly} which are directories, scripts inside which will be executed every hour/day/week/month, with root privilege.

    root can always use the crontab command; regular users may or may not be granted access. When you edit the crontab file with the command crontab -e and save it, crond checks it for basic validity but does not guarantee your crontab file is correctly formed. There is a file called cron.deny which will specify which users cannot use cron. The cron.deny file location is system dependent and can be deleted which will allow all users to use cron.

    If the computer is not powered on or crond daemon is not running, and the date/time for a command to run has passed, crond will not catchup and run past queries.

    crontab particulars, how to formulate a command:

    A crontab command is represented by a single line. You cannot use \ to extend a command over multiple lines. The hash (#) sign represents a comment which means anything on that line is ignored by cron. Leading whitespace and blank lines are ignored.

    Be VERY careful when using the percent (%) sign in your command. Unless they are escaped \% they are converted into newlines and everything after the first non-escaped % is passed to your command on stdin.

    There are two formats for crontab files:

    • User crontabs

       # Example of job definition:
       # .---------------- minute (0 - 59)
       # |  .------------- hour (0 - 23)
       # |  |  .---------- day of month (1 - 31)
       # |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
       # |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)
       # |  |  |  |  |
       # *  *  *  *  *   command to be executed
      
    • System wide /etc/crontab and /etc/cron.d fragments

       # Example of job definition:
       # .---------------- minute (0 - 59)
       # |  .------------- hour (0 - 23)
       # |  |  .---------- day of month (1 - 31)
       # |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
       # |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)
       # |  |  |  |  |
       # *  *  *  *  * user-name  command to be executed
      

    Notice that the latter requires a user-name. The command will be run as the named user.

    The first 5 fields of the line represent the time(s) when the command should be run. You can use numbers or where applicable day/month names in the time specification.

    Read the rest at the sourceFrom Server Fault: asked by Eric Leschinski, answered by Eric Leschinski (CC BY-SA 4.0)

  20. How can I get the size of an Amazon S3 bucket?

    This can now be done trivially with just the official AWS command line client:

    aws s3 ls --summarize --human-readable --recursive s3://bucket-name/
    

    Official Documentation: AWS CLI Command Reference (version 2)

    This also accepts path prefixes if you don't want to count the entire bucket:

    aws s3 ls --summarize --human-readable --recursive s3://bucket-name/directory
    

    From Server Fault: asked by powdahound, answered by philwills (CC BY-SA 4.0)

  21. Showing total progress in rsync: is it possible?

    There is now an official way to do this in rsync (version 3.1.0 protocol version 31, tested with Ubuntu Trusty 14.04).

    #> ./rsync -a --info=progress2 /usr .
        305,002,533  80%   65.69MB/s    0:00:01  xfr#1653, ir-chk=1593/3594)
    

    I tried with my /usr folder because I wanted this feature for transferring whole filesystems, and /usr seemed to be a good representative sample.

    The --info=progress2 gives a nice overall percentage, even if it's just a partial value. In fact, my /usr folder is more than 6 gigs:

    #> du -sh /usr
    6,6G    /usr/
    

    and rsync took a lot of time to scan it all. So almost all the time the percentage I've seen was about 90% completed, but nonetheless it's comforting to see that something is being copied :)

    References:

    From Server Fault: asked by Aron Rotteveel, answered by Avio (CC BY-SA 4.0)

  22. How can I use environment variables in Nginx.conf?

    From the official Nginx docker file:

    Using environment variables in nginx configuration:

    Out-of-the-box, Nginx doesn't support using environment variables inside most configuration blocks.

    But envsubst may be used as a workaround if you need to generate your nginx configuration dynamically before nginx starts.

    Here is an example using docker-compose.yml:

    image: nginx
    volumes:
     - ./mysite.template:/etc/nginx/conf.d/mysite.template
    ports:
     - "8080:80"
    environment:
     - NGINX_HOST=foobar.com
     - NGINX_PORT=80
    command: /bin/bash -c "envsubst < /etc/nginx/conf.d/mysite.template > /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'" 
    

    The mysite.template file may then contain variable references like this :

    listen ${NGINX_PORT};
    

    Update:

    But you know this caused to its Nginx variables like this:

    proxy_set_header        X-Forwarded-Host $host;
    

    damaged to:

    proxy_set_header        X-Forwarded-Host ;
    

    So, to prevent that, i use this trick:

    I have a script to run Nginx, that used on the docker-compose file as command option for Nginx server, i named it run_nginx.sh:

    #!/usr/bin/env bash
    export DOLLAR='$'
    envsubst < nginx.conf.template > /etc/nginx/nginx.conf
    nginx -g "daemon off;"
    

    And because of defined new DOLLAR variable on run_nginx.sh script, now content of my nginx.conf.template file for Nginx itself variable is like this:

    proxy_set_header        X-Forwarded-Host ${DOLLAR}host;
    

    And for my defined variable is like this:

    server_name  ${WEB_DOMAIN} www.${WEB_DOMAIN};
    

    Also here, there is my real use case for that.

    From Server Fault: asked by Hugo Rodger-Brown, answered by Omid Raha (CC BY-SA 3.0)

  23. How do I get the current Unix time in milliseconds in Bash?

    This:

    date +%s 
    

    will return the number of seconds since the epoch.

    This:

    date +%s%N
    

    returns the seconds and current nanoseconds.

    So:

    date +%s%N | cut -b1-13
    

    will give you the number of milliseconds since the epoch - current seconds plus the left three of the nanoseconds.

    and from MikeyB - echo $(($(date +%s%N)/1000000)) (dividing by 1000 only brings to microseconds)

    From Server Fault: asked by Richard, answered by warren (CC BY-SA 4.0)

  24. Why it is recommended to run only one process in a container?

    Lets forget the high-level architectural and philosophical arguments for a moment. While there may be some edge cases where multiple functions in a single container may make sense, there are very practical reasons why you may want to consider following "one function per container" as a rule of thumb:

    • Scaling containers horizontally is much easier if the container is isolated to a single function. Need another apache container? Spin one up somewhere else. However if my apache container also has my DB, cron and other pieces shoehorned in, this complicates things.
    • Having a single function per container allows the container to be easily re-used for other projects or purposes.
    • It also makes it more portable and predictable for devs to pull down a component from production to troubleshoot locally rather than an entire application environment.
    • Patching/upgrades (both the OS and the application) can be done in a more isolated and controlled manner. Juggling multiple bits-and-bobs in your container not only makes for larger images, but also ties these components together. Why have to shut down application X and Y just to upgrade Z?
      • Above also holds true for code deployments and rollbacks.
    • Splitting functions out to multiple containers allows more flexibility from a security and isolation perspective. You may want (or require) services to be isolated on the network level -- either physically or within overlay networks -- to maintain a strong security posture or comply with things like PCI.
    • Other more minor factors such as dealing with stdout/stderr and sending logs to the container log, keeping containers as ephemeral as possible etc.

    Note that I'm saying function, not process. That language is outdated. The official docker documentation has moved away from saying "one process" to instead recommending "one concern" per container.

    From DevOps Stack Exchange: asked by Evgeny Zislis, answered by Jon (CC BY-SA 3.0)

  25. What is an artifactory?

    Artifactory is a product by JFrog that serves as a binary repository manager. That said very often one will use a 'artifactory' as a synonym of the more general binary repository, much like many people use Frigidaire or fridge to denote the refrigerator regardless if it is a Frigidaire brand or not.

    The binary repository is a natural extension to the source code repository, in that it will store the outcome of your build process, often denoted as artifacts. Most of the times one would not use the binary repository directly but through a package manager that comes with the chosen technology.

    In most cases these will store individual application components that can later be assembled into a full product - thus allowing a build to be broken in smaller chunks, making more efficient use of resources, reducing build times, better tracking of binary debug databases etc.

    Here are some of the most popular package managers that can be managed using a binary repository:

    • Java: jar, ear, war etc has Maven and the official MavenCentral. There are many other package managers that will use the maven binary repository format as well (ivy, gradle etc).
    • .Net: nuget for .NET components (DLL and EXE) but can also be used as a distribution mechanism under windows thorugh systems like Chocolatey. Newer versions of Powershell can also leverage this to distribute powershell modules though the powershell gallery of which one could build a local distribution with a binary repository and a repository in nuget format. Also check OneGet if Windows distribution management is of interest to you.
    • In JavaScript: we have npm which is one of the most popular, will require nodejs.
    • In python: there is pip and the official package index pypi, which one can also create a local instance through binary repository that will support the format.

    This list is far from complete, just gives an idea of what's out there.

    The binary repository can allow to host all of these under one roof, making their management much simpler for teams. Note that you do not need a very large team to start reaping benefits from binary package management. The initial investment is not very large and the benefits are felt immediately. Especially now that more and more platforms, frameworks and languages are integrating this dependency management directly in them. Their biggest advantage I have found however was to create an environment that your programmers will find natural and comfortable making it essential. It helps you as a devops creating a solid tool-chain and it helps them making the overall experience fit naturally in their stack of choice.

    As I said earlier there are many products out there that can serve as binary package managers, some more generic than others in their target usage, varying also widely in their accessibility and prices.

    Read the rest at the sourceFrom DevOps Stack Exchange: asked by Pierre.Vriens, answered by Newtopian (CC BY-SA 4.0)

  26. Cleanest way to prematurely exit a Jenkins Pipeline job as a success?

    Please note: The following works for scripted pipelines only. For a solution for declarative pipelines see @kgriffs' answer.

    ---

    Figured it out. Outside of any stages (otherwise this will just end the particular stage as a success) do the following;

    if( $VALUE1 == $VALUE2 ) {
       currentBuild.result = 'SUCCESS'
       return
    }
    

    return will stop the stage or node you're running on which is why running it outside of a stage is important, while setting the currentBuild.result prevents it from failing.

    From DevOps Stack Exchange: asked by Alex, answered by Alex (CC BY-SA 4.0)

  27. What is the definition of "cattle not pets"?

    Randy Bias chronicles the history of the term stating that it probably originated in 2011 or 2012 when Bill Baker used the analogy when describing "scale-up" vs. "scale-out" architectural strategies. Bias adopted this into his presentations about cloud architectural patterns:

    In the old way of doing things, we treat our servers like pets, for example Bob the mail server. If Bob goes down, it’s all hands on deck. The CEO can’t get his email and it’s the end of the world. In the new way, servers are numbered, like cattle in a herd. For example, www001 to www100. When one server goes down, it’s taken out back, shot, and replaced on the line.

    Bias continues to define Pets as

    Servers or server pairs that are treated as indispensable or unique systems that can never be down. Typically they are manually built, managed, and “hand fed”. Examples include mainframes, solitary servers, HA loadbalancers/firewalls (active/active or active/passive), database systems designed as master/slave (active/passive), and so on.

    and cattle as

    Arrays of more than two servers, that are built using automated tools, and are designed for failure, where no one, two, or even three servers are irreplaceable. Typically, during failure events no human intervention is required as the array exhibits attributes of “routing around failures” by restarting failed servers or replicating data through strategies like triple replication or erasure coding. Examples include web server arrays, multi-master datastores such as Cassandra clusters, multiple racks of gear put together in clusters, and just about anything that is load-balanced and multi-master.

    Fundamentally, what Bias and Baker are trying to convey is there has to be a transition from how we treat servers from being "Unique Snowflakes" with names and emotional attachments, to a model whereby if we have a problem with the server we create a replacement and destroy the problematic server.

    Finally, it is probably worth mentioning that in regulated environments taking a server out the back and shooting it may not be optimal. In these cases it is often advantageous to "freeze" the server, for example using docker pause to freeze a container. This can then be used to perform a Root Cause Analysis as part of the Incident or Problem Management Process.

    From DevOps Stack Exchange: asked by Richard Slater, answered by Richard Slater (CC BY-SA 3.0)

  28. How to decrypt Jenkins passwords from credentials.xml?

    Luckily there is a hudson.util.Secret.decrypt() function which can be used for this, so:

    1. In Jenkins, go to: /script page.
    2. Run the following command:

      println(hudson.util.Secret.decrypt("{XXX=}"))
      

      or:

      println(hudson.util.Secret.fromString("{XXX=}").getPlainText())
      

      where {XXX=} is your encrypted password. This will print the plain password.

      To do opposite, run:

      println(hudson.util.Secret.fromString("some_text").getEncryptedValue())
      

    Source: gist at tuxfight3r/jenkins-decrypt.groovy.

    Alternatively check the following scripts: tweksteen/jenkins-decrypt, menski/jenkins-decrypt.py.

    For more details, check: Credentials storage in Jenkins.

    From DevOps Stack Exchange: asked by kenorb, answered by kenorb (CC BY-SA 3.0)

  29. Downloading Docker Images from Docker Hub without using Docker

    It turned out that the Moby Project has a shell script on the Moby Github which can download images from Docker Hub in a format that can be imported into Docker:

    The usage syntax for the script is given by the following:

    download-frozen-image-v2.sh target_dir image[:tag][@digest] ...
    

    The image can then be imported with tar and docker load:

    tar -cC 'target_dir' . | docker load
    

    To verify that the script works as expected, I downloaded an Ubuntu image from Docker Hub and loaded it into Docker:

    user@host:~$ bash download-frozen-image-v2.sh ubuntu ubuntu:latest
    user@host:~$ tar -cC 'ubuntu' . | docker load
    user@host:~$ docker run --rm -ti ubuntu bash
    root@1dd5e62113b9:/#
    

    In practice I would have to first copy the data from the internet client (which does not have Docker installed) to the target/destination machine (which does have Docker installed):

    user@nodocker:~$ bash download-frozen-image-v2.sh ubuntu ubuntu:latest
    user@nodocker:~$ tar -C 'ubuntu' -cf 'ubuntu.tar' .
    user@nodocker:~$ scp ubuntu.tar user@hasdocker:~
    

    and then load and use the image on the target host:

    user@hasdocker:~ docker load ubuntu.tar
    user@hasdocker:~ docker run --rm -ti ubuntu bash
    root@1dd5e62113b9:/#
    

    From DevOps Stack Exchange: asked by igal, answered by igal (CC BY-SA 4.0)

  30. What's the difference between travis-ci.org and travis-ci.com?

    Travis CI originally created two separated platforms to differentiate between private repos / paid (travis-ci.com) and public repos / free (travis-ci.org).

    However, as of May 2018, new users and projects (both private and public) should only use travis-ci.com (see this blog post). Note that travis-ci.org will be closed down completely on December 31st, 2020 (see this newsletter).

    Although still in beta—which is a bit weird since travis-ci.org will be shut down soon—Travis CI provides a well-documented migration guide.

    From DevOps Stack Exchange: asked by Stevoisiak, answered by beatngu13 (CC BY-SA 4.0)

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.